Autocoder

JavaScript Closures Interview Questions

Last updated 2026-11-19

Closures are one of the most reliably asked JavaScript topics. A good answer explains lexical scope, shows a counter or private variable, and can solve the famous loop-and-setTimeout puzzle without hesitation. Harder rounds ask you to write once, memoize, debounce or curry from scratch.

This page goes through the concept first and then the utilities and traps built on it, with the exact console output for each snippet so you can check your reasoning.

LevelFresher to 4 years
FocusLexical scope, private state, higher-order utilities
RuntimeBrowser and Node.js

A definition you can give in one breath

A closure is a function together with the lexical environment in which it was created, so it keeps access to the variables of its outer scopes even after those scopes have finished running. The captured thing is the variable binding, not a snapshot of its value.

That second sentence explains almost every closure puzzle.

Related topics

Closures rely on scope rules explained in hoisting and scope, and they underpin callbacks and promises. Overall preparation is in how to crack a JavaScript interview.

JavaScript Closures Interview Questions: questions with worked answers

  1. 1

    What is a closure? Give an example.

    easy

    A closure is a function that remembers the variables of the scope where it was defined. In the example, the inner function keeps using count after makeCounter has returned. Each call to makeCounter creates a fresh scope, so counters are independent. Nothing outside can touch count directly, which gives private state.

    javascript
    function makeCounter() {
      let count = 0;
      return () => ++count;
    }
    const a = makeCounter(), b = makeCounter();
    console.log(a(), a(), b());   // 1 2 1
  2. 2

    Predict the output: setTimeout inside a for loop with var.

    medium

    var is function-scoped, so all three callbacks share one i. The timers run after the loop ends, when i is 3. Declaring the counter with let creates a new binding per iteration, so each callback sees its own value. Pre-ES6 fixes wrapped the body in an IIFE or used bind to pass the current value.

    javascript
    for (var i = 0; i < 3; i++) setTimeout(() => console.log(i), 0);
    // 3 3 3
    for (let j = 0; j < 3; j++) setTimeout(() => console.log(j), 0);
    // 0 1 2
    for (var k = 0; k < 3; k++) {
      ((n) => setTimeout(() => console.log(n), 0))(k);
    }
    // 0 1 2
  3. 3

    How do closures create private variables?

    easy

    Declare the state inside a function and return only the functions that may use it. Callers cannot read or write the variable except through the returned API. Modern classes offer true private fields with a hash prefix, but closures remain the common pattern for the module pattern and factory functions.

    javascript
    function account(balance) {
      return {
        deposit(n) { balance += n; return balance; },
        get balance() { return balance; },
      };
    }
    const acc = account(100);
    acc.deposit(50);
    console.log(acc.balance, acc.hasOwnProperty("balance"));  // 150 true
    console.log(Object.keys(acc));   // ['deposit', 'balance']
  4. 4

    Write a once function that lets a callback run only one time.

    medium

    Keep a flag and the result in the closure. The first call runs the function and stores its result, and later calls return the stored result. This is a classic closure utility.

    javascript
    function once(fn) {
      let done = false, result;
      return function (...args) {
        if (!done) { done = true; result = fn.apply(this, args); }
        return result;
      };
    }
    const init = once(() => { console.log("init"); return 42; });
    console.log(init(), init());   // init, then 42 42
  5. 5

    Implement a memoize function.

    medium

    Store results in a Map keyed by the arguments. For single primitive arguments the argument itself works as a key. For several arguments, join them or use JSON.stringify, noting that this fails for functions and cycles. Memoisation is only safe for pure functions, and the cache grows without limit unless you bound it.

    javascript
    function memoize(fn) {
      const cache = new Map();
      return (...args) => {
        const key = JSON.stringify(args);
        if (!cache.has(key)) cache.set(key, fn(...args));
        return cache.get(key);
      };
    }
    const slow = memoize((n) => { console.log("compute", n); return n * 2; });
    console.log(slow(4), slow(4));   // compute 4, then 8 8
  6. 6

    Implement currying: add(1)(2)(3) and a generic curry.

    medium

    A curried function takes one argument at a time and returns another function until enough arguments have been collected. The generic version compares the number of arguments received so far with fn.length.

    javascript
    const curry = (fn) => function c(...args) {
      return args.length >= fn.length
        ? fn(...args)
        : (...more) => c(...args, ...more);
    };
    const add = curry((a, b, c) => a + b + c);
    console.log(add(1)(2)(3), add(1, 2)(3), add(1)(2, 3));   // 6 6 6
  7. 7

    Write a debounce function.

    hard

    Debounce delays calling fn until a quiet period has passed since the last call, which suits search boxes and resize handlers. Keep the timer id in the closure, clear it on each call and set a new one. Preserve this and arguments. A throttle, in contrast, allows a call at most once per interval.

    javascript
    function debounce(fn, wait) {
      let t;
      return function (...args) {
        clearTimeout(t);
        t = setTimeout(() => fn.apply(this, args), wait);
      };
    }
    const log = debounce((x) => console.log("run", x), 100);
    log(1); log(2); log(3);    // after 100ms: run 3
  8. 8

    What does an IIFE do, and how does it relate to closures?

    medium

    An immediately invoked function expression runs as soon as it is defined and creates a private scope, so variables inside do not leak into the enclosing scope. Before ES modules and let, it was the way to build modules and to capture loop variables. The functions it returns remain closures over that private scope.

    javascript
    const counter = (() => {
      let n = 0;
      return { inc: () => ++n, get: () => n };
    })();
    counter.inc(); counter.inc();
    console.log(counter.get());   // 2
  9. 9

    Predict the output: closures capture variables, not values.

    hard

    Both functions below close over the same x. Calling set changes the variable, so get sees the new value. A closure created earlier does not hold a copy from that moment.

    javascript
    function pair() {
      let x = 1;
      return [() => x, (v) => { x = v; }];
    }
    const [get, set] = pair();
    console.log(get());   // 1
    set(5);
    console.log(get());   // 5
  10. 10

    How can closures cause memory leaks?

    hard

    A closure keeps its whole captured scope alive for as long as the function is reachable. If a long-lived function, such as an event listener or a cache entry, references a large object, that object cannot be garbage collected. Engines optimise away unused variables in many cases, but you cannot rely on it. Remove listeners when finished, null out large references and avoid holding DOM nodes in long-lived closures.

  11. 11

    What is the module pattern, and what replaced it?

    medium

    The module pattern wraps state and functions in an IIFE and returns a public API, giving encapsulation without classes. ES modules replaced it: each file has its own scope, exports are explicit, and imports are live bindings. The same closure idea still powers factory functions and hooks-style APIs.

  12. 12

    Predict the output of a closure inside a method that loses this.

    hard

    A regular function passed as a callback gets its own this, which is not the object. An arrow function takes this from the enclosing scope lexically, which is another way scope is captured. That is why arrow functions suit callbacks inside methods.

    javascript
    const o = {
      name: "obj",
      regular() { return [1].map(function () { return this?.name; }); },
      arrow() { return [1].map(() => this.name); },
    };
    console.log(o.regular(), o.arrow());   // [ undefined ] [ 'obj' ]
  13. 13

    What is a stale closure and where does it appear?

    medium

    A stale closure reads an outdated value because the function was created before the variable changed and was never re-created. In React, an effect or timer callback that captures a state value from an earlier render keeps seeing that old value. Fix it with dependency arrays, functional state updates or refs. See React interview questions.

Frequently asked questions

Do closures only exist in JavaScript?

No. Most languages with first-class functions and lexical scope have them, including Python, Swift and Go. The interview focus on JavaScript is because of loops, callbacks and var scoping.

Is every function a closure?

Technically every function captures its defining environment, but people use the word for the case where a function uses variables from an outer function that has already returned.

What is the difference between closure and scope?

Scope is the set of visible variables at a point in the code. A closure is a function bundled with the scope it was created in so that scope persists after the outer function returns.

Why does the var loop print the same number?

All callbacks share one function-scoped variable, and it holds its final value when the callbacks run.

Related guides

More in Programming Language Interview Questions by Language

See all in this section