DEV Community

Shashi Bhushan Kumar
Shashi Bhushan Kumar

Posted on

What is a Closure in JavaScript? Explained Simply

Closures are often introduced as an “advanced concept,” but the idea is surprisingly simple.

A closure happens when a function retains access to variables from its outer scope even after the outer function has executed.

Think of it like this

You create a private variable inside a function.
Then you return another function that can still access that variable.

Even though the outer function is done,
the inner function keeps the variable alive.

Example

function outer() {
  let count = 0;

  return function () {
    count++;
    console.log(count);
  };
}

const counter = outer();

counter(); // 1
counter(); // 2

Enter fullscreen mode Exit fullscreen mode

Here, count is preserved between function calls.

That’s a closure.

Why Closures Matter

Data privacy

Maintaining state

Functional programming patterns

Closures are not magic.
They’re just JavaScript remembering scope.

Top comments (0)