What are closures in JavaScript?

EasyPhone Screen
MetaFrontend Engineer
312

Explain what closures are in JavaScript. Provide an example of when you would use a closure and explain how it works.

2 Answers

234
Top Answer

A closure is a function that remembers the variables from its outer scope even after the outer function has finished executing.

Simple Example

function createCounter() {
  let count = 0;  // This variable is "enclosed"

  return function() {
    count++;
    return count;
  };
}

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

The inner function "closes over" the count variable and keeps it alive.

Practical Use Cases

  1. Data privacy - Variables can't be accessed directly from outside
  2. Function factories - Create specialized functions
  3. Event handlers - Preserve state between events
  4. Partial application - Pre-fill some arguments
JSTeacher
156

Common interview trap - closures in loops:

// Bug: All buttons log 3
for (var i = 0; i < 3; i++) {
  buttons[i].onclick = function() {
    console.log(i);  // Always 3!
  };
}

// Fix 1: Use let (block scope)
for (let i = 0; i < 3; i++) {
  buttons[i].onclick = function() {
    console.log(i);  // 0, 1, 2
  };
}

// Fix 2: Create closure with IIFE
for (var i = 0; i < 3; i++) {
  (function(j) {
    buttons[j].onclick = function() {
      console.log(j);  // 0, 1, 2
    };
  })(i);
}

This is a classic interview question!

InterviewCoach

Share Your Answer

Help others by sharing your knowledge and experience with this question.

Coming soon...

Related Questions

View all

More from Meta

View all