What is Lexical Scope?
Lexical Scope means a function can access variables from its own scope and parent scope based on where the function is defined in the code.
const name = "Somnath";function greet() { console.log(name);}greet();
When JavaScript looks for name, it checks: It finds name in the global scope inside greet() and then parent (global) scope. This is lexical scope.
What is Closure ?
A closure is a function that has access to variables from its outer (lexical) scope even after the outer function has returned.
function outer() { let count = 0; return function inner() { count++; console.log(count); };}const increment = outer();increment(); // 1increment(); // 2increment(); // 3// outer() creates count.// outer() returns inner().// Normally, count would disappear when outer() finishes.// But inner() keeps a reference to count.// So count is remembered between calls.// This "remembering" is called a closure.
Leave a comment