Command Palette

Search for a command to run...

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

Private state with rules

The buttons are closures too: each arrow remembers wallet. Click Spend until the rule stops you.

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?

Private state with rules

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

150
Not enough money
120
undefined
120