Skip to content

JavaScript Closures

A closure is a function that retains access to variables from its outer scope, even after the outer function has finished executing.

closure.js
function createCounter() {
let count = 0;
return {
increment() {
count++;
return count;
},
getCount() {
return count;
}
};
}
const counter = createCounter();
console.log(counter.increment()); // 1
console.log(counter.increment()); // 2
console.log(counter.getCount()); // 2
  1. Data privacy - Create private variables
  2. Function factories - Generate functions with different configurations
  3. Event handlers - Retain references to data when handling events
  4. Callbacks - Pass context into async operations
  • Closures hold a reference to the variable, not the value at creation time
  • Be careful with closures in loops - use let instead of var
  • Memory leaks can occur if closures hold references to large objects unnecessarily