JavaScript1 min read

JavaScript Closures Explained for Coding Interviews

Understand JavaScript closures, lexical scope, private state, factory functions, loop gotchas, and memory considerations with step-by-step interview exercises.

Pairlet Team•Published: •Updated:

Closures are one of the most frequently tested concepts in JavaScript technical interviews. Understanding how closures work under the hood helps candidates write cleaner stateful functions and spot memory retention bugs.

What is a Closure?

A closure is created whenever a function is defined inside another function, granting the inner function access to the outer function's variable environment (lexical scope).

JAVASCRIPT
function outerFunction(outerVariable) {
  return function innerFunction(innerVariable) {
    console.log(`Outer: ${outerVariable}, Inner: ${innerVariable}`);
  };
}

const closureFn = outerFunction("Hello");
closureFn("World"); // Outer: Hello, Inner: World

Practical Applications of Closures

1. Private State & Data Encapsulation

Before ES6 private class fields (#private), closures were the primary mechanism for creating private variables.
JAVASCRIPT
function createBankAccount(initialBalance) {
  let balance = initialBalance; // Private state
  
  return {
    deposit(amount) {
      if (amount > 0) balance += amount;
      return balance;
    },
    withdraw(amount) {
      if (amount > 0 && amount <= balance) {
        balance -= amount;
        return balance;
      }
      return "Insufficient funds";
    },
    getBalance() {
      return balance;
    }
  };
}

2. Function Memoization

Closures allow caching expensive function call results based on input parameters.
JAVASCRIPT
function memoize(fn) {
  const cache = new Map();
  return function (...args) {
    const key = JSON.stringify(args);
    if (cache.has(key)) {
      return cache.get(key);
    }
    const result = fn.apply(this, args);
    cache.set(key, result);
    return result;
  };
}

*Practice the Memoize coding task on Pairlet.*

Classic Interview Loop Gotcha

What does the following code log?

JAVASCRIPT
for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 100);
}
// Logs: 3, 3, 3

Why? var is function-scoped. All three callbacks share the exact same i reference, which is 3 by the time the timers fire.

Fix 1: Use let (Block Scope)

``javascript for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100); } // Logs: 0, 1, 2 ``

Fix 2: Create a Closure via IIFE

``javascript for (var i = 0; i < 3; i++) { ((index) => { setTimeout(() => console.log(index), 100); })(i); } // Logs: 0, 1, 2 ``

Practice Closure Problems Live

Collaborate with candidates live on stateful closure exercises. Create a Pairlet interview room.

Frequently Asked Questions

What is a closure in simple terms?

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

Practice Relevant Coding Problems
Practice Live Coding

Conduct Live Coding Interviews in the Browser

No candidate sign-up required. Create a room, share the link, and code together in real time with shared code execution.

Related Articles