JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsjavascript
Next
javascript
mid
closures

What is a closure in JavaScript and why are they useful?

closures
scope
functions
data-privacy
state
Quick Answer

A closure is a function that has access to variables from its outer (enclosing) scope, even after the outer function has returned. They're useful for data privacy, state management, and creating function factories.

Detailed Explanation

A closure is created when a function is defined inside another function, and the inner function references variables from the outer function's scope.

How Closures Work:

  • When a function is created, it gets a reference to its lexical environment
  • This environment includes all variables that were in scope at the time of creation
  • The function maintains this reference even after the outer function returns

Common Use Cases:

  1. Data Privacy: Create private variables that can't be accessed directly
  2. State Preservation: Maintain state between function calls
  3. Function Factories: Generate specialized functions
  4. Callbacks & Event Handlers: Preserve context in async operations
  5. Partial Application & Currying: Pre-fill function arguments

Code Examples

Basic closure example
function createCounter() {
  let count = 0; // Private variable
  
  return function() {
    count++;
    return count;
  };
}

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

// count is not accessible directly
console.log(count); // ReferenceError

Resources

MDN - Closures

docs

JavaScript.info - Closure

article

You Don't Know JS - Scope & Closures

book

Related Questions

How does the 'this' keyword work in JavaScript?

mid
this
Next
What are Promises in JavaScript and how do they work?