← Back to blog

Understanding JavaScript Closures

Closures are one of those concepts that seem confusing until you see them in action. Once you understand them, they click forever.

A closure is simply a function that remembers the variables from where it was defined, even after that scope has exited.

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

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

The inner function closes over count, keeping access to it long after counter() has finished running. That’s the closure.