Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 3.6 — Closures
JavaScript · Example 3 of 3 ES2015+

The loop + var bug, and the let fix

All the var callbacks share one i (or k), which is 3 when they run. let gives every iteration its own variable.

A closure is a function together with the variables of the place where it was created; the function keeps using those variables even after the outer function has finished, which gives you counters, private state and function factories, and explains the classic var loop bug.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write makeGreeter(greeting) that returns a function taking a name, so makeGreeter("Hi")("Asha") returns "Hi, Asha".

02

Write makeCounter(start = 0) that returns { increment, decrement, value } where value() returns the current count.

03

Write once(fn) that returns a function which calls fn only the first time and returns the same result on every later call.

Explain it without notes

01

What is a closure? Explain with a counter example.

02

Why do two counters made by the same factory not share their count?

03

Explain why a for loop with var and setTimeout prints the same number three times, and two ways to fix it.

04

How do closures provide private state, and what is a downside?

The loop + var bug, and the let fix ES2015+

Console

(nothing was printed)

Expected console output

[ 3, 3, 3 ]
[ 0, 1, 2 ]
var k: 3
var k: 3
var k: 3
let m: 0
let m: 1
let m: 2