Back To Posts
JavaScript Closures – The Power of Lexical Scoping

Sanket Joshi | September 14, 2024

JavaScript Closures – The Power of Lexical Scoping

Closures are a powerful concept in JavaScript that allow functions to access variables from their outer lexical environment, even after that outer function has returned. Closures enable useful patterns such as data encapsulation, memoization, and function factories.

What is a Closure?

A closure occurs when an inner function remembers variables from its outer function, even after the outer function has completed execution.

Example of a Closure

Consider this example:

function outer() {
  const outerVariable = 'I am from outer scope';

  return function inner() {
    console.log(outerVariable);
  };
}

const closureFunc = outer();
closureFunc();  // Outputs: 'I am from outer scope'