Back to practice
#2Medium·technical·1 min read

Explain Closures in JavaScript

javascriptclosuresscopefunctions
Share

The Question

"Can you explain what closures are in JavaScript and give an example of when you'd use one?"

Why They Ask

Closures are fundamental to JavaScript. This question tests whether you understand scope, lexical environment, and practical patterns like data privacy and function factories.

What is a Closure?

A closure is a function that retains access to variables from its outer (enclosing) scope, even after that outer function has returned.

Example

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

Here, increment and getCount close over the count variable. Even after createCounter finishes executing, the returned methods still have access to count.

Practical Use Cases

  • Data privacy — Encapsulate state without exposing it globally
  • Function factories — Create specialized functions from a template
  • Event handlers — Preserve context in callbacks
  • Memoization — Cache results in a closed-over variable

Common Follow-up: Loop + Closure Gotcha

// Bug: all callbacks log 3
for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 100);
}
 
// Fix: use let (block scope) or an IIFE
for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 100);
}

Key Takeaway

A closure is created every time a function is defined inside another function. Understanding closures unlocks patterns like module pattern, currying, and partial application.

You might also like