EasyCore JS📖 Theory Question

Explain closures with a practical example.

💡

Hint

A function that remembers its outer scope after the outer function returns

Full Answer

A closure is a function that retains access to its lexical scope even after the outer function has returned.

function makeCounter() {
  let count = 0;
  return {
    increment: () => ++count,
    decrement: () => --count,
    value:     () => count
  };
}
const counter = makeCounter();
counter.increment(); // 1
counter.increment(); // 2

Real-world uses: data encapsulation, factory functions, event handlers with state, memoization, partial application.

💡 Classic gotcha: var in a for-loop closure — all callbacks share the same variable. Fix with let or IIFE.

More Core JS Questions

EasyWhat is the difference between var, let, and const?EasyWhat is hoisting in JavaScript?EasyExplain the event loop, call stack, and microtask queue.EasyWhat is the difference between == and ===?

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint