Skip to main content

Closure

Closure is a function that has access to its own scope, the scope of the outer function, and the global scope.

Closures can be used to emulate private properties and methods.

Every JavaScript function creates a new lexical environment. This environment has a reference to its outer environment, forming a scope chain

The scope chain is a process of how Javascript looks for variables. When code needs to access a variable, JavaScript looks at the current scope. If not found, it moves up the scope chain to the outer scope and continues until it reaches the global scope. If the variable is still not found, a reference error is thrown.

Example: Counter

function getCounter() {
let counter = 0;
return function () {
return counter++;
};
}

let count = getCounter();
console.log(count()); // 0
console.log(count()); // 1
console.log(count()); // 2