Home
JavaScript
Closures in JavaScript
April 11, 2024
1 min

A closure in JavaScript occurs when a function retains access to variables from its lexical (outer) scope, even after the outer function has finished executing. In short:

How Closures Work

JavaScript uses lexical scoping, meaning a function can access variables defined where it was created.

function outer() {
let count = 0;
return function inner() {
count++;
return count;
};
}
const increment = outer();
increment(); // 1
increment(); // 2

Even though outer() has completed, inner() still has access to count. That preserved variable is the closure.

Data Encapsulation with Closures

Closures enable data encapsulation by keeping variables private and exposing only controlled APIs.

function createCounter() {
let count = 0; // private
return {
increment() {
count++;
},
getValue() {
return count;
}
};
}
const counter = createCounter();
counter.increment();
counter.getValue(); // 1
counter.count; // undefined

Here, count cannot be accessed or modified directly, ensuring safer and cleaner code.

Why Closures Matter

Closures are essential for:

  • Private state (module pattern)
  • Callbacks and event handlers
  • Stateful logic (timers, counters, toggles)
  • Modern frameworks (React hooks rely heavily on closures)

Tags

#Javascript

Share

Related Posts

JavaScript
Debouncing vs Throttling
August 30, 2025
1 min
© 2026, All Rights Reserved.
Powered By

Social Media

githublinkedinyoutube