JS Guide
HomeQuestionsTopicsCompaniesResources
BookmarksSearch

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

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsjavascript
Next

Learn the concept

Closures

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 exampleJavaScript
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

Real-World Applications

Use Cases

Data Privacy / Module Pattern

Creating private variables and methods inaccessible from outside, enabling encapsulation without classes

React Hooks

useState and useEffect internally rely on closures to preserve state between renders and associate state with component instances

Memoization

Caching expensive computation results using closure-held cache objects to avoid redundant calculations

Mini Projects

Private Counter Module

beginner

Build a module with private state exposed through public increment, decrement, and getCount methods using closures

Memoize Utility

intermediate

Implement a generic memoize function using closures to cache function results based on arguments

Industry Examples

React

Hooks like useState and useEffect use closures to associate state with component instances across re-renders

Lodash

_.memoize and _.once use closures to cache results and limit function invocations

Node.js

CJS module system wraps each file in a closure (function(exports, require, module, __filename, __dirname) {...}) for encapsulation

Resources

MDN - Closures

docs

JavaScript.info - Closure

article

You Don't Know JS - Scope & Closures

book

Related Questions

What is the difference between block scope and function scope?

mid
scope

How does the 'this' keyword work in JavaScript?

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