A closure is the combination of a function and the lexical environment within which that function was declared
for example,
function greet(Say){
return (
function(name){
console.log(Say + ' ' + name);
}
)
}
Now I'm I can do something like this,
greet('Hi')('Alex')
This line will return the string 'Hi Alex'
Now I'm going to do something like this,
var sayGreet = greet('Hi');
If I console.log(sayGreet) it will be a function.
Now tell me where is this sayGreet variable defined? It is on the global level. Or in the other word global execution context.
Now let's do,
sayGreet('Alex')
inside this sayGreet function, we have a console.log(Say + " " + name)
. We know name
is Alex but what about Say
? There is no sign of Say
at this moment because the greet function already completed execution and returned a function.
Even though javascript still have the ability to refer to the Say value. Even it is completed the execution. This Say
value can only be access by inner functions or nested functions.
This is call closure. A single function cannot be closure. There should be an outer lexical environment too.