Clousure and Lexcical Scope
Example
function father(){
let Property = "House"
return function son(){
let sonProperty = "Car"
return `My owner ship in ${sonProperty} and ${Property}`
}
}
const result = father(); // returns the 'son' function
console.log(result());
Closure
A closure is created when an inner function (son) retains access to variables from its outer function (father) even after the outer function has finished executing.
In this case, son still has access to Property even though father() has already returned. That's a closure.
Lexcical
Lexical Scope means a function's scope is determined by its position in the code (its location in the source file), and it has access to variables declared in its outer scopes.
Important
Closure + Loop (Classic Interview Example)
for (var i = 0; i < 3; i++) {
setTimeout(function () {
console.log(i);
}, 1000);
}
// Output: 3, 3, 3 (because of var + closure)
✅ Fix with Closure:
for (var i = 0; i < 3; i++) {
(function (j) {
setTimeout(function () {
console.log(j);
}, 1000);
})(i);
}
// Output: 0, 1, 2
Comments
Post a Comment