JavaScript Closures — exercises and bug fixes
5 hands-on exercises and 5 find-the-bug challenges for the JavaScript Closures lesson. Every one is checked automatically in the browser — write the code, run it, and the tests tell you what still fails.
Exercises(5)
- 1
Build a counter
easy10 minBuild a counter with a closure and call it three times, joining the results.
- 2
Keep a value private
easy10 minStore a balance in a closure, deposit 50 onto 100, and show the balance.
- 3
Build a function factory
easy10 minMake a multiplier that triples, then use it on 14.
- 4
Separate closures
easy10 minShow that two counters do not share their count, joined by a comma.
- 5
Remember whether it ran
medium10 minUse a closure so a setup function only ever returns its first answer.
Find the bug(5)
- 1
Fix the counter that resets
easy8 minThe count is declared inside the returned function, so it starts again every call.
- 2
Fix the balance that is not kept
easy8 minThe deposit works on a copy, so the balance never grows.
- 3
Fix the factory that returns a number
easy8 minThe outer function should return a function, not a value.
- 4
Fix the shared count
easy8 minThe count sits outside the factory, so both counters share it.
- 5
Fix the loop closure
easy8 minWith var, all three functions share one variable.
Ready to write the code?
The editor, the automatic checks and the worked solutions open up with an account.
Open the workspace