Advanced Concepts

Closure in JavaScript: Explanation with Example

What is a Closure?

A closure is formed when an inner function retains access to variables from its outer (enclosing) function's scope, even after the outer function has finished executing.

Example

function outer() {
    let count = 0;
    return function inner() {
        count++;
        return count;
    };
}

const counter = outer();
console.log(counter()); // 1
console.log(counter()); // 2

Why Closures are Useful

  • Data privacy — creating variables that can't be accessed directly from outside.
  • Maintaining state between function calls, as seen in counters and memoized functions.
  • Powering patterns like the module pattern and function factories.

Ready to master real-world JavaScript development?

Learn JavaScript hands-on with mentor-led, live sessions.

Explore Course