DEV Community

Mark Tony
Mark Tony

Posted on

JS - Closures

Closures in JavaScript is when a function "remembers" the variable from the place where it was created, even after that outer scope has finished running.

function outer() {
  let count = 0; // variable in outer's scope

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

  return inner;
}

const counter = outer();
counter(); // 1
counter(); // 2
counter(); // 3
Enter fullscreen mode Exit fullscreen mode

Here's what's happening:

  1. outer() runs, creates a variable count, and defines inner().
  2. outer() returns inner, and its execution finishes.
  3. Normally, you'd expect count to be gone once outer returns — its scope is done.
  4. But inner still has access to count, because it "closed over" that variable when it was created.

Each call to counter() doesn't reset count to 0 — it keeps incrementing the same count variable, tucked away inside the closure.

Why this happens

JavaScript functions retain a reference to the lexical scope (the scope where they were textually defined), not just at creation but for their entire lifetime. So inner carries a link back to outer's variable environment wherever it goes.

Top comments (0)