Build a counter with a closure and call it three times, joining the results.
Acceptance criteria
- 1.#out should show 1,2,3.
JavaScript Tutorial · JavaScript Scope & Hoisting
These 10 tasks go with the JavaScript Closures chapter. 5 of them ask you to build something small from scratch; 5 give you code that is already broken and ask you to work out why. Set aside about 90 minutes for the whole set, though you can do them in any order.
Nothing here is marked by a person. When you press Submit, the editor checks your code against the points listed under each task and tells you straight away what passed and what didn't (you need a free account to submit). If you get stuck, there are hints, and a worked solution once you've had a go. The first 2 tasks are free; the rest are part of the practice plan.
If it's been a while since you read the chapter, here is how it starts: “A JavaScript closure is a function that remembers the variables around it, even after the outer function has finished.” .
1.Build a counterexercise · easy · 10 min
Build a counter with a closure and call it three times, joining the results.
Passes when: #out should show 1,2,3.
2.Keep a value privateexercise · easy · 10 min · practice plan
Store a balance in a closure, deposit 50 onto 100, and show the balance.
Passes when: #out should show 150.
3.Build a function factoryexercise · easy · 10 min · practice plan
Make a multiplier that triples, then use it on 14.
Passes when: #out should show 42.
4.Separate closuresexercise · easy · 10 min · practice plan
Show that two counters do not share their count, joined by a comma.
Passes when: #out should show 2,1.
5.Remember whether it ranexercise · medium · 10 min · practice plan
Use a closure so a setup function only ever returns its first answer.
Passes when: #out should show first.
6.Fix the counter that resetsbug fix · easy · 8 min
The count is declared inside the returned function, so it starts again every call.
Passes when: #out should show 1,2,3.
7.Fix the balance that is not keptbug fix · easy · 8 min · practice plan
The deposit works on a copy, so the balance never grows.
Passes when: #out should show 150.
8.Fix the factory that returns a numberbug fix · easy · 8 min · practice plan
The outer function should return a function, not a value.
Passes when: #out should show 42.
9.Fix the shared countbug fix · easy · 8 min · practice plan
The count sits outside the factory, so both counters share it.
Passes when: #out should show 2,1.
10.Fix the loop closurebug fix · easy · 8 min · practice plan
With var, all three functions share one variable.
Passes when: #out should show 1,2,3.
Between them these tasks cover Closures, Private state and Function factories.
Looking for a different chapter? See every practice set, or switch to the interview theory questions.