Skip to article content
FrontendXLesson 03 / 30

Functions and Closures

Build a precise mental model of JavaScript values, scope, functions, objects, arrays and asynchronous behavior, then implement and debug real utilities from first principles instead of memorizing outputs.

beginner · about 40 minutes · 6 exercises

  • Predict
  • Explain
  • Implement
  • Debug
  • Test
  • Interview

What you will be able to do

#
  • Compare function declarations, function expressions and arrow functions.
  • Explain what a closure captures and when it is created.
  • Use closures to build private state and factories.

Overview

#

Functions are values

A function is a value you can store, pass and return. A function declaration is hoisted and named. A function expression is assigned to a binding and is not hoisted with a value. An arrow function is a shorter expression form with no own this, arguments or prototype, which makes it a poor fit for methods that need their own this.

What a closure is

A closure is a function together with the lexical environment it was defined in. When a function references a variable from an outer scope, the engine keeps that binding alive for as long as the function can be called. The closure captures the binding, not a snapshot of its value.

snippet.js
function makeCounter() {
  let count = 0;
  return () => ++count;
}
const next = makeCounter();
console.log(next(), next()); // 1 2

Independent state per call

Each call to a factory function creates a new lexical environment, so each returned closure has its own private state. Two counters made by the same factory do not share a count.

Closures in practice

Closures power event handlers, memoization, debouncing, module private state and the classic loop-with-timers puzzle. When you see a function that remembers something between calls, you are looking at a closure.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Predict

    What do these two independent counters log?

    Read the code, then choose the best answer. The reference explanation stays hidden until you respond.
    stimulus.javascript
    function makeCounter() {
      let count = 0;
      return () => ++count;
    }
    const a = makeCounter();
    const b = makeCounter();
    console.log(a(), a(), b());
    Choose the best answer
  2. Exercise 2Explain

    Explain why the returned function can still read `count` after `makeCounter` has finished running.

    starter.javascript
    function makeCounter() {
      let count = 0;
      return () => ++count;
    }

    Reveal the reference answer
    reference.javascript
    The inner arrow function references count from the enclosing function scope. The engine keeps that lexical environment alive because the returned function still refers to it. The environment is not garbage collected while a reachable function can access it, so count survives between calls.

    Authored expected output: 1

    A closure keeps the environment, not just the variable. The lifetime of the captured binding is extended to the lifetime of the closure.

  3. Exercise 3Implement

    Implement `once(fn)` that returns a wrapper calling fn at most one time and returning the first result on every later call. Running `const init = once(() => { console.log('run'); return 42; }); console.log(init(), init());` should print `run` then `42 42`.

    starter.javascript
    function once(fn) {
      // your code here
    }

    Reveal the reference answer
    reference.javascript
    function once(fn) {
      let called = false;
      let result;
      return function (...args) {
        if (!called) {
          called = true;
          result = fn.apply(this, args);
        }
        return result;
      };
    }

    Authored expected output: run 42 42

    The wrapper closes over called and result. The first call runs fn and stores the result; later calls skip fn and return the stored value, which is why 'run' prints only once.

  4. Exercise 4Debug

    This factory is supposed to give each returned object its own private total, but both objects share one total. Fix it.

    starter.javascript
    var total = 0;
    function makeAccount() {
      return {
        add: (n) => { total += n; },
        read: () => total,
      };
    }
    const x = makeAccount();
    const y = makeAccount();
    x.add(5);
    console.log(x.read(), y.read());

    Reveal the reference answer
    reference.javascript
    function makeAccount() {
      let total = 0;
      return {
        add: (n) => { total += n; },
        read: () => total,
      };
    }
    const x = makeAccount();
    const y = makeAccount();
    x.add(5);
    console.log(x.read(), y.read());

    Authored expected output: 5 0

    In the buggy version total is declared once outside makeAccount, so every account closes over the same binding and both read 5. Moving the declaration inside the factory creates a fresh binding per call, so x keeps its own total of 5 and y stays at 0.

  5. Exercise 5Test

    Write tests that prove two counters from the same factory keep independent state.

    starter.javascript
    function makeCounter() {
      let count = 0;
      return () => ++count;
    }

    Reveal the reference answer
    reference.javascript
    const a = makeCounter();
    const b = makeCounter();
    if (a() !== 1) throw new Error('a first');
    if (a() !== 2) throw new Error('a second');
    if (b() !== 1) throw new Error('b independent');
    if (a() !== 3) throw new Error('a third after b');
    console.log('counters are independent');

    Authored expected output: counters are independent

    Interleaving calls on a and b proves the two closures do not share a binding. If they shared one, b's first call would return 3.

  6. Exercise 6Interview

    Define a closure in one sentence and describe two production uses.

    starter.javascript
    function debounce(fn, ms) {
      let timer;
      return (...args) => {
        clearTimeout(timer);
        timer = setTimeout(() => fn(...args), ms);
      };
    }

    Reveal the reference answer
    reference.javascript
    A closure is a function bundled with the lexical environment it was defined in, so it can keep reading and writing bindings from that environment after the outer function returns. Two production uses: debouncing input handlers, where the timer id is private state, and memoization, where the cache lives in a closure.

    The answer should name the environment, not just the function, and should tie the concept to a real feature rather than a puzzle.

Common misconceptions

#
  • A closure copies the value of a captured variable at creation time.
  • Arrow functions have their own this like regular functions.
  • Closures only matter for interview puzzles and not real code.

Follow-up practice

#
  • javascript-foundations-objects-and-prototypes
  • javascript-foundations-async-event-loop

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.