JavaScript AcademyProfessional Engineering
Level 2 · Core DevelopmentModule 10: Scope and JavaScript BehaviorLesson 48 of 150About 45 minutes

Lesson 48: Closures

01Opening question

A counter function returns a number that keeps going up between calls, but nothing outside can change it directly. Where is that number stored?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

The returned function still reaches count after makeCounter has finished.

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

03Objective and prerequisites

Learning objective: Create closures that remember variables after their outer function returns, use them for private state and function factories, and avoid the loop closure trap.

You need: Lesson 47: Lexical environments, Lesson 19: Nested loops and patterns

Skills practised: Closures.

04Explanation

A closure is a function together with the variables it can reach from where it was written.

When an inner function is returned or stored, it keeps those outer variables alive, even after the outer function has finished.

Each call of the outer function creates a separate set of variables, so two counters made by makeCounter() count independently.

Closures give private state: code outside can use the returned functions but cannot read or change the variable directly.

05Definitions

Closure
A function plus the outer variables it keeps access to from where it was defined.
Private state
Data reachable only through the functions that close over it.
Function factory
A function that creates and returns configured functions.
Captured variable
An outer variable that a closure keeps alive and can read or change.

Open the full glossary

06Visual learning object

Closure visualizer. Step through creating two counters and watch each keep its own count in a separate environment.

Loading the interactive object…

Open the full Closure visualizer page with its guided experiment.

07Examples

ex-048-01Independent counters Browser-executable JavaScript

Each factory call creates its own count.

function makeCounter() {
  let count = 0;
  return () => ++count;
}
const likes = makeCounter();
const views = makeCounter();
likes();
likes();
views();
console.log(likes(), views());
Sample input
None
Expected output
3 2
Common mistake
Expecting both counters to share one count.
Try this
Add a reset function by returning an object with increment and reset.
Source
examples/ex-048-01-counter.js (repository pending publication)

ex-048-02Function factory Browser-executable JavaScript

The returned function remembers the rate it was made with.

function makeDiscount(percent) {
  return (price) => price - (price * percent) / 100;
}
const tenOff = makeDiscount(10);
const halfOff = makeDiscount(50);
console.log(tenOff(80), halfOff(80));
Sample input
None
Expected output
72 40
Common mistake
Calling makeDiscount(10, 80) and expecting a price.
Try this
Make a makeTax(rate) factory too.
Source
examples/ex-048-02-factory.js (repository pending publication)

ex-048-03Private state Browser-executable JavaScript

Only the returned methods can change the balance.

function createWallet(start) {
  let balance = start;
  return {
    spend(amount) {
      if (amount > balance) return "Insufficient funds";
      balance -= amount;
      return `Spent ${amount}`;
    },
    getBalance: () => balance
  };
}
const wallet = createWallet(20);
console.log(wallet.spend(15));
console.log(wallet.spend(10));
console.log(wallet.getBalance(), wallet.balance);
Sample input
None
Expected output
Spent 15 Insufficient funds 5 undefined
Common mistake
Expecting wallet.balance to exist; balance is a variable, not a property.
Try this
Add a deposit method.
Source
examples/ex-048-03-private-wallet.js (repository pending publication)

ex-048-04The loop closure trap Browser-executable JavaScript

var shares one variable; let gives each iteration its own.

const withVar = [];
for (var i = 0; i < 3; i++) withVar.push(() => i);
const withLet = [];
for (let j = 0; j < 3; j++) withLet.push(() => j);
console.log(withVar.map((f) => f()));
console.log(withLet.map((f) => f()));
Sample input
None
Expected output
[3, 3, 3] [0, 1, 2]
Common mistake
Using var in loops that create callbacks.
Try this
Rewrite the var version with forEach instead.
Source
examples/ex-048-04-loop-trap.js (repository pending publication)

ex-048-05Variables, not snapshots Browser-executable JavaScript

A closure reads the variable's current value when it runs.

let greeting = "Hello";
const greet = (name) => `${greeting}, ${name}`;
console.log(greet("Ada"));
greeting = "Welcome back";
console.log(greet("Ada"));
Sample input
None
Expected output
Hello, Ada Welcome back, Ada
Common mistake
Assuming the closure froze the value at creation time.
Try this
Capture a fixed copy by passing greeting into a factory.
Source
examples/ex-048-05-captures-variable.js (repository pending publication)

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Fix the shared counter

Move state into the factory so each counter is separate.

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

Greeter factory

Write a function that returns a configured function.

function makeGreeter(greeting) {
  // TODO: return a function that takes a name
}
const hi = makeGreeter("Hi");
console.log(hi("Ada"));

Attempt limiter

Keep private state in a closure.

// Write createLimiter(max)

09Prediction

Commit to an answer first, then run the real code to compare.

function make() {
  let n = 0;
  return { inc: () => ++n, get: () => n };
}
const c = make();
c.inc();
c.inc();
console.log(c.get(), make().get());

What is printed?

10Debugging investigation

Every tab opens the last panel

Three tab handlers are created in a loop. Clicking the first tab should open panel 0, but every handler opens panel 3, which does not exist.

const handlers = [];
for (var i = 0; i < 3; i++) {
  handlers.push(() => `open ${i}`);
}
const results = handlers.map((h) => h());
console.log(results.join(", "));

More cases in the Debugging Detective Laboratory

11Practical scenario

Configured event handlers

A page creates a click handler for each product button. Each handler is a closure over its product's id, so the same handler code knows which product it belongs to without reading the page again.

const handlers = ["p1", "p2"].map((id) => () => `add ${id} to cart`);
console.log(handlers[1]());

12Knowledge check

1. What is printed?

function counter() { let n = 0; return () => ++n; }
const c = counter();
console.log(c(), c());
  • 1 2
  • 1 1
  • 2 2
  • 0 1

2. What does a closure keep access to?

  • Only global variables
  • The variables in scope where the function was defined
  • A copy of the caller's variables
  • Nothing after the outer function returns

3. What is printed?

const fns = [];
for (var i = 0; i < 3; i++) fns.push(() => i);
console.log(fns.map((f) => f()));
  • [0, 1, 2]
  • [3, 3, 3]
  • [undefined, undefined, undefined]
  • An error

4. Why is wallet.balance undefined?

function createWallet() { let balance = 10; return { get: () => balance }; }
const wallet = createWallet();
console.log(wallet.balance);
  • balance is a captured variable, not a property
  • balance was never set
  • Arrow functions cannot return
  • The wallet is frozen

5. What is printed?

const times = (f) => (n) => n * f;
const double = times(2);
console.log(double(3), double(4));
  • 6 8
  • 6 6
  • 3 4
  • NaN NaN

6. How should a module keep a login attempt count that other code must not change directly?

  • A global variable
  • A let inside a factory, exposed only through functions
  • A property on window
  • A var in a loop

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • Fix the shared counter: Prints 3 1; Fresh counter starts at 1
  • Greeter factory: Prints Hi, Ada!; Another greeting
  • Attempt limiter: Prints the attempts; State is private; Limiters are independent
  • ex-048-01: output matches the documented expected output
  • ex-048-02: output matches the documented expected output
  • ex-048-03: output matches the documented expected output
  • ex-048-04: output matches the documented expected output
  • ex-048-05: output matches the documented expected output

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-02-core-development/module-10-scope-and-javascript-behavior/lesson-048-closures/. Every example on this page is generated from those files.

The GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Academy) has not been published yet, so these links will work once it is. Until then, use the ZIP download above.

15Summary and next steps

  • A closure is a function plus the outer variables it can reach.
  • Captured variables stay alive after the outer function returns.
  • Each factory call creates separate state.
  • Use let in loops that create callbacks.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation closures
Context: I am learning closures in JavaScript.
Task: Explain closures with a counter and a discount factory, and why each counter has its own state.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code prediction closures drill
Context: I have practised closures.
Task: Give me six closure snippets, including the var loop trap, and ask what each prints.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debugging closures bug
Context: My callbacks all use the last value from a loop.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generation closures practice
Context: I finished the closures exercises.
Task: Create three exercises that use closures for private state and factories.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code review closures review
Context: Here is my code that uses closures.
Task: Review my code for global state that could be a closure and for closures that hold large data unnecessarily.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.