Closures in Javascript
Closure: is when a function can remember its lexical scope even when that function is executing outside its lexical scope.
If you are not able to understand this jibber-jabber, you are not the only one. Closure is the most confusing part for most of the JS developers.
So according to the definition of closure, we first need to understand what is lexical scope. Lexical scope is the nested group of functions in which the inner functions have access to all the variables and other resources of its parent function.
For example:
function foo(){
var a=2
function foo2(){
var b=3
console.log(b,a)
}
foo2()
}foo()Output:3,2
Here foo2 has access to the variable of foo(it’s parent function)
This is all about the lexical scope. Let’s get back to closure.
Let’s take an example
function foo(){
var a=2
function bar(){
console.log(b,a)
}
return bar;
}var baz=foo()
baz() //2
bar() is executed but outside of its declared lexical scope.
After foo() is executed, we would expect the entire foo() will go away and the engine employs a garbage collector that frees up memory once its no longer used.
So closure doesn’t let this happen. The inner scope of bar() is still in use and thus, doesn’t go away because bar() has a lexical scope over foo() to keep the scope alive for bar() to refer whenever required.
Closures are more common than we realize.
To give an instance, let’s take setTimeout
function wait(message){
setTimeout(function timer(){
console.log(message)
})
}wait('Hello')
Here, setTimeout has a reference to some parameter called fn or func or something of that sort. Engine goes to invoke that function which in turn invokes the timer function.