Function with there lexical scope form a bundle that’s called lexical scope.
In JavaScript, a closure is a function that reference variable from its outer scope, effectively preventing the outer scope inside its inner scope. This fundamental concept that can greatly enhance the power and flexibility of your code
Essentially, closures allow a function to ‘remember’ its lexical scope even when the function is executed outside that lexical scope
const value = 1;
function doSomething() {
let data = [1,2,3,4,5,6,7,8,9,10,11];
return data.filter(item => item % value === 0);
}
Let’s understand Lexical scope
Lexical scope is the ability for a function scope to access variable from the parent scope. We call the child function to be lexically bound by that of the parent function.
Here a simple example for closures
function x() {
var a = 7;
function y() {
console.log(a);
}
var z = x();
console.log(z);
}
//.......
z();
Output: 7
Some of the cases
function x() {
var a = 7;
function y() {
console.log(a);
}
a = 100;
return y;
}
//.......
z();
Output: 100
Here it print 100. Becouse before function return value it’s refence value is changed.
Uses of Closures:
- Module Design Patttern
- Curring
- IIFE
- memoization
- Maintaining state in async world
- setTimeouts
- Iterators
- and many more