LearnFrenzy
Sign in Take a free test
JS

JavaScript Programming · Topic 18 of 25

Closures Questions and Concepts

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Closures · Study material

A closure is a function together with the variables of the scope it was created in. Because JavaScript scope is lexical, an inner function keeps access to its outer function's variables even after the outer function has returned. Closures are behind private state, function factories, memoization, once, debounce and throttle, event handlers, React hooks and almost every callback you write – and "what is a closure?" followed by a tricky output question is a near-certain interview pair. This topic covers how closures work, the classic loop problem, stale closures, memory and practical patterns. Then test yourself with 60 practice questions – 15 MCQs, 20 predict-the-output puzzles, 15 debugging questions and 10 coding problems – every one run on Node.js.

What a closure is

Every time a function is created, it records a reference to the environment (the variables) around it. When it runs later – even long after that environment's function has finished – it can still read and update those variables. There is no special syntax: any function that uses variables from an outer scope forms a closure.

function makeGreeting(greeting) {
  const punctuation = "!";
  // The inner function uses greeting and punctuation – variables of makeGreeting…
  return function (name) {
    return `${greeting}, ${name}${punctuation}`;
  };
}
// …and still can after makeGreeting has returned: that is a closure
const hello = makeGreeting("Hello");
console.log(hello("Asha"), makeGreeting("Namaste")("Ravi"));

Output

Hello, Asha! Namaste, Ravi!

One environment per call

Each call of the outer function creates a new set of variables, so two counters made by two calls are independent. Functions created during the same call share that call's variables – which is how inc, dec and get can work on one private count.

function makeCounter() {
  let count = 0;
  // Three closures created in the same call share ONE count
  return { inc: () => ++count, dec: () => --count, get: () => count };
}
const a = makeCounter();      // each call creates a NEW count
const b = makeCounter();
a.inc(); a.inc(); a.dec();
b.inc();
console.log(a.get(), b.get());

Output

1 1

Closures capture variables, not values

A closure holds a live link to the variable. If the variable changes before the closure runs, the closure sees the new value. That is why closures created in a let loop behave well (each iteration has its own variable) and why closures over one shared variable all see its final value.

let message = "first";
const show = () => message;     // remembers the variable, not its value at this moment
message = "second";
console.log(show());

function makeAdders() {
  const adders = [];
  for (let i = 1; i <= 3; i++) adders.push((x) => x + i);   // let: each closure gets its own i
  return adders;
}
console.log(makeAdders().map((add) => add(10)));

Output

second
[ 11, 12, 13 ]

The loop question

With var, the whole loop shares one variable, so every closure created in it sees the value it has after the loop. The fixes: declare the loop variable with let (a new binding per iteration), or – the pre-ES6 way – pass the current value into an IIFE so each closure gets its own copy.

const viaVar = [], viaLet = [], viaIife = [];
for (var i = 0; i < 3; i++) viaVar.push(() => i);               // one shared i → all see 3
for (let j = 0; j < 3; j++) viaLet.push(() => j);               // a new j per iteration
for (var k = 0; k < 3; k++) viaIife.push(((n) => () => n)(k));  // pre-ES6 fix: copy k into n
console.log(viaVar.map((f) => f()), viaLet.map((f) => f()), viaIife.map((f) => f()));

Output

[ 3, 3, 3 ] [ 0, 1, 2 ] [ 0, 1, 2 ]

Private state

Variables of the outer function cannot be reached from outside – only through the functions that close over them. This gives true privacy (older than class #private fields) and lets the API enforce rules, such as checking the old password before changing it.

function createPassword(initial) {
  let secret = initial;           // no one outside can read or change these directly
  let attempts = 0;
  return {
    check(guess) { attempts++; return guess === secret; },
    change(oldPw, newPw) {
      if (oldPw !== secret) return false;
      secret = newPw;
      return true;
    },
    get attempts() { return attempts; },
  };
}
const pw = createPassword("lf@123");
console.log(pw.check("abc"), pw.change("lf@123", "new#456"), pw.check("new#456"), pw.attempts, pw.secret);

Output

false true true 2 undefined

Memoization

A closure can keep a cache between calls. memoize returns a function whose private Map remembers results for arguments it has already seen – a big win for expensive pure functions.

function memoize(fn) {
  const cache = new Map();              // lives as long as the returned function
  return (...args) => {
    const key = JSON.stringify(args);
    if (!cache.has(key)) cache.set(key, fn(...args));
    return cache.get(key);
  };
}
let work = 0;
const slowPow = (b, e) => { work++; return b ** e; };
const fastPow = memoize(slowPow);
console.log(fastPow(2, 10), fastPow(2, 10), fastPow(3, 3), "computed", work, "times");

Output

1024 1024 27 computed 2 times

Live values vs snapshots (stale closures)

A closure that reads a variable sees its current value. A closure that received a value as a parameter (or captured a variable that is later replaced by a new one) keeps the old value – a stale closure. This is a common source of bugs with timers and with React hooks such as useEffect and setInterval.

function createLogger() {
  let level = "info";
  const logNow = (msg) => `[${level}] ${msg}`;                       // reads level when called
  const snapshot = ((saved) => (msg) => `[${saved}] ${msg}`)(level);   // copied level once
  return { setLevel: (l) => (level = l), logNow, snapshot };
}
const log = createLogger();
log.setLevel("debug");
console.log(log.logNow("hi"), log.snapshot("hi"));

Output

[debug] hi [info] hi

Common mistakes

  • var in loops with callbacks – every callback sees the final value; use let.
  • Putting the state outside the factory – all "instances" share one variable.
  • Expecting a snapshot – closures read the current value of a variable.
  • Expecting a live value from a copy – a value passed in as a parameter will not update.
  • Shadowing the private variable – let count = 0 inside reset() creates a new variable.
  • Capturing large data by accident – it stays in memory as long as the closure does.
  • Assuming closures capture this – only arrow functions take this lexically.

Key points to remember

  • Closure = function + the variables of the scope it was created in.
  • Every outer call creates new variables; closures from one call share them.
  • Closures capture variables (live), not values.
  • let in loops gives each iteration its own variable; var shares one.
  • Closures give private state, factories, memoization, once, debounce.
  • Captured variables stay in memory while the closure is reachable.
  • this is not part of a closure – except for arrow functions.

Frequently asked questions

Is every function a closure?

Technically every function keeps a reference to the environment it was created in. In practice we say "closure" when a function uses variables from an outer scope that outlives the outer function's execution.

Do closures cause memory leaks?

Not by themselves. Variables are kept only while the closure is reachable (for example, still registered as an event listener). Remove listeners and clear timers you no longer need, and avoid capturing large objects you do not use.

Closures or classes for private data?

Both work. Classes with #private fields are clearer for many instances with shared methods; closures are lighter for small helpers, factories and functional code.

Where can I learn more?

Read JavaScript Closures and Functions in the JavaScript tutorial, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About JavaScript Programming

Why it matters

  • JavaScript runs every web page and, with Node.js, servers, tools and APIs – it is the most used language in the world
  • Front-end, full-stack and MERN roles test JavaScript first, and many campus coding rounds allow it
  • "Predict the output" questions on hoisting, closures, this, coercion and the event loop are interview favourites
  • Modern ES6+ – let/const, arrow functions, destructuring, promises and async/await – is what companies expect from freshers

Who it is for

  • College students (B.Tech, BCA, MCA, B.Sc CS) learning web development and preparing for semester exams and viva
  • Freshers preparing for campus placements, online assessments and front-end interviews
  • Developers moving to React, Angular, Vue or Node.js who need strong core JavaScript
  • Anyone revising ES6 and asynchronous JavaScript before an interview

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • Topic-wise MCQs on concepts and ES6 features
  • "Predict the output" puzzles – hoisting, coercion, closures, promises and timers
  • "Find the error" debugging: SyntaxError, ReferenceError, TypeError and silent logic bugs
  • Coding problems with solutions and real output, every one run on Node.js – run any study example in your browser

Asked in

  • Campus placements
  • TCS, Infosys, Wipro, Accenture, Cognizant tests
  • Front-end developer interviews
  • MERN / full-stack interviews
  • Online coding assessments
  • University practicals

How to use this section

  1. Read the study material of a topic and run the examples in the browser.
  2. Practise the four exercises – MCQs, output, debugging, coding problems – each marked Easy, Medium or Hard, and read every explanation.
  3. Revise with the interview questions and cheat sheet, then move to the next topic.

Search LearnFrenzy

Esc

Quick links