Home Courses Closure in JavaScript Explained with Counter App Example

Closure in JavaScript Explained with Counter App Example

What is a Closure?

A closure is a feature in JavaScript.

A closure is created when an inner function remembers and accesses variables from its outer function, even after the outer function has finished execution.


Basic Example


function outer() {
let message = "This is outer function scope";

function inner() {
console.log(message);
}

return inner;
}

let result = outer();
result(); // Output: This is outer function scope

Explanation:

  1. outer() runs and returns the inner function
  2. Normally, message should be destroyed after outer() finishes
  3. But inner() still remembers message
  4. This behavior is called a closure


Key Concept

Even after the outer function is executed:

  1. Its variables are still accessible inside the inner function
  2. That memory is preserved due to closure


Benefits of Closures

1. Data Privacy

Variables inside the outer function are not accessible globally.


console.log(message); // Error

Only the inner function can access them.

2. State Preservation

Closures allow you to maintain state across function calls.


Real Use Case – Counter Example


function counterApp() {
let data = 0;

return {
increment: function () {
console.log(++data);
},
decrement: function () {
console.log(--data);
}
};
}

let counter = counterApp();


HTML Buttons


<button onclick="counter.increment()">Increment</button>
<button onclick="counter.decrement()">Decrement</button>

How it works:

  1. data is private
  2. It cannot be accessed directly
  3. But it is still remembered and updated through closures


Output Behavior

Clicking buttons:

  1. Increment → 1, 2, 3...
  2. Decrement → decreases value

Even though counterApp() has already executed, data is still preserved.


Why Closures Are Important

Closures are widely used in:

  1. Event handlers
  2. Callbacks
  3. Data hiding
  4. Functional programming
  5. Real-world applications like counters, timers, and modules


Share this lesson: