Skip to main content

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. 1

    Build a counter

    easy10 min

    Build a counter with a closure and call it three times, joining the results.

  2. 2

    Keep a value private

    easy10 min

    Store a balance in a closure, deposit 50 onto 100, and show the balance.

  3. 3

    Build a function factory

    easy10 min

    Make a multiplier that triples, then use it on 14.

  4. 4

    Separate closures

    easy10 min

    Show that two counters do not share their count, joined by a comma.

  5. 5

    Remember whether it ran

    medium10 min

    Use a closure so a setup function only ever returns its first answer.

Find the bug(5)

  1. 1

    Fix the counter that resets

    easy8 min

    The count is declared inside the returned function, so it starts again every call.

  2. 2

    Fix the balance that is not kept

    easy8 min

    The deposit works on a copy, so the balance never grows.

  3. 3

    Fix the factory that returns a number

    easy8 min

    The outer function should return a function, not a value.

  4. 4

    Fix the shared count

    easy8 min

    The count sits outside the factory, so both counters share it.

  5. 5

    Fix the loop closure

    easy8 min

    With 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