An anonymous function is one which does not have any name to it, rest is same as the normal functions in Javascript.
Here is an ex.
Case 1:
This is just some normal/regular javascript function
var sayHello = function iWillSayHello(name){
var fullName = "Hello, " + name;
console.log(fullName);
}
sayHello("ABC"); // prints---> Hello, ABC
Case 2:
This is Annonymous function,
It is the same function with the same behavior as above,
var sayHello = function(name){
var fullName = "Hello, " + name;
console.log(fullName);
}
sayHello("ABC"); // prints---> Hello, ABC
Case 3:
If(I think) by "anonymous function" you mean IIFE(Immediately Invoked Function Execution),
that is this,
(function(name){
var fullName = "Hello, " + name;
console.log(fullName);
})(); // prints---> Hello, ABC
The difference here is, In "Case 1" and "Case 2" you have to call the function explicitly, BUT in "Case 3" it is invoked automatically (i.e. with "()" at the end you are calling it as it is declared).
It will be called as compiler reaches that line.
Clouser, on the other hand, is a function inside a function.
What makes a Clouser a special in js, is it still can access the values of the variable from the "local scope" of the outer function even if the outer function has returned.
Clouser = function + outer context
here is a simple example,
function outerSayHello(firstName){
var fullName = firstName;
function innerSayHello(lastName){
console.log("Hello, ", fullName + " " + lastName);
}
return innerSayHello;
}
console.log("1-------------------------");
var sayHello = outerSayHello("A");
sayHello("B");
//Hello, A B
console.log("2-------------------------");
var sayHello1 = outerSayHello("A1");
sayHello1("B1");
//Hello, A1 B1
console.log("3-------------------------");
sayHello("b");
//Hello, A b
console.log("4-------------------------");
sayHello1("b1");
//Hello, A1 b1
console.log("5-------------------------");
outerSayHello("ABC")("XYZ");
//Hello, ABC XYZ
to better understand these let's console the sayHello variable
console.log("6-------------------------",sayHello);
/*
innerSayHello(lastName){
console.log("Hello, ", fullName + " " + lastName);
}
*/
What it means is sayHello variable has pointer/reference to the innerSayHello function.
And because innerSayHello is relying on fullName variable, it will still be maintained on the heap, and fullName and innerSayHello still be on the stack even after outerSayHello returns.
So in the heap, it will create multiple references for fullname and innerSayHello.