Hey mates on the internet (β'β‘'β)
Now, itβs time to talk about closures.
What is Closure?
A closure is a function that has access to its outer function scope even after the outer function has returned. This means a closure can remember and access variables and arguments of its outer function even after the function has finished.
Before we dive into closures, letβs first understand the lexical scope.
What is a Lexical Scope?
A lexical scope or static scope in JavaScript refers to the accessibility of the variables, functions, and objects based on their physical location in the source code. For example:
let a = 'global';
function outer() {
let b = 'outer';
function inner() {
let c = 'inner'
console.log(c); // prints 'inner'
console.log(b); // prints 'outer'
console.log(a); // prints 'global'
}
console.log(a); // prints 'global'
console.log(b); // prints 'outer'
inner();
}
outer();
console.log(a); // prints 'global'
Here the inner
function can access the variables defined in its own scope, the outer
functionβs scope, and the global
scope. And the outer
function can access the variable defined in its own scope and the global
scope.
So a scope chain of the above code would be like this:
Global {
outer {
inner
}
}
Notice that inner
function is surrounded by the lexical scope
of outer function
which is, in turn, surrounded by the global scope
. Thatβs why the inner function can access the variables defined in outer function and the global scope.
Quiz β Test Your Knowledge
What would the below code print out?
var name = 'John'
function greet (name) {
return (function () {
console.log('Hello ' + name)
})
}
var sayHello = greet(name)
name = 'Sam'
sayHello()
The answer is Hello John.
Yes, even though we altered the value of name to 'Sam' before we invoked sayHello. Itβs as if, the value of name was captured before it was reassigned to 'Sam'.
Yes, even though we altered the value of name to 'Sam' before we invoked sayHello. Itβs as if, the value of name was captured before it was reassigned to 'Sam'.
That is exactly what happened β this is closure in action.
Top comments (0)