⏱ 0:01est. 3 min
Chapter 46- Understanding Closures
Notes
Example 1
function greet(whattosay){
return function(name){
console.log(whattosay + ‘ ' + name);
}
}
//We are invoking a function that returns a function so that we can invoke the returned function
greet(‘Hi')(‘Tony'); // OUTPUT : Hi Tony
Example 2
function greet(whattosay){
return function(name){
console.log(whattosay + ‘ ' + name);
}
}
//sayHi will be the function which was returned by calling greet
var sayHi = greet(‘Hi');
sayHi(‘Tony') //OUTPUT : Hi Tony;
Now how does sayHi function knows the whattosay variable
Explanation -
When this code starts we have global execution context then we invokes greet function and created new execution context of greet() and that variable which was passed to it whattosay is sitting in it's variable environment, it returns a new function object and creates a function on the fly and returns it. After that return the greet execution context is popped off the stack.
Under normal circumstances js engine clears out the memory space using garbage collection but at the moment that execution context finishes that memory space is still there of (whattosay) variable, It's still hanging around now we move on the global execution context then we invoke the function sayHi(). It's an anonymous function and that creates a new execution context and we have name variable to it so it ends up in memory.
When we hits a line console.log(whattosay + ‘ ' + name); when this code is invoked js engine sees whattosay variable it goes up the scope chain, it goes to outer lexical environment in this case to look for the variable since it couldn't find it inside the function itself. sayHi has reference to the variable whattosay which is available in the memory space of it's outer environment.This phenomena is called closure.
Closures are simply the feature of the javascript programming language. We don't have to worry if it's out environment is still running. Js engine handle the reference to variables in lexical out environment.
The js engine creates the closure we are just taking advantage of it.