Closures in JavaScript

A closure is created when a function is defined inside another function and gains access to the outer function’s variables — even after the outer function has finished execution.

Key points:

  • The inner function 'remembers' the environment (variables) in which it was created.

  • Closures enable private variables — variables that cannot be accessed from outside the function directly.

Simple Example:

javascript
1function outerFunction() { 2 let privateVariable = 'I'm private'; 3 4 function innerFunction() { 5 console.log(privateVariable); // Accesses the variable from outerFunction 6 } 7 8 return innerFunction; 9} 10 11const closureFunc = outerFunction(); 12closureFunc(); // Output: 'I'm private'

Even though outerFunction has finished running, closureFunc still remembers privateVariable.

Real-world use case: Private Counters

javascript
1function createCounter() { 2 let count = 0; 3 4 return { 5 increment: function() { 6 count++; 7 console.log(count); 8 }, 9 decrement: function() { 10 count--; 11 console.log(count); 12 } 13 }; 14} 15 16const counter = createCounter(); 17counter.increment(); // 1 18counter.increment(); // 2 19counter.decrement(); // 1

Here, count is private — it can only be modified using increment and decrement.