Skip to main content

JavaScript WeakMap and WeakSet — exercises and bug fixes

5 hands-on exercises and 5 find-the-bug challenges for the JavaScript WeakMap and WeakSet 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

    Store against an object

    easy10 min

    Use an object as a WeakMap key and read the value back.

  2. 2

    Check for a key

    easy10 min

    Report whether the object is in the WeakMap.

  3. 3

    Reject a string key

    easy10 min

    Catch the error when a string is used as a key.

  4. 4

    Show there is no size

    easy10 min

    Report that a WeakMap has no size property.

  5. 5

    Use a WeakSet

    medium10 min

    Add an object and check a different one is not present.

Find the bug(5)

  1. 1

    Fix the primitive key

    easy8 min

    A WeakMap key must be an object.

  2. 2

    Fix the attempt to loop

    easy8 min

    A WeakMap is not iterable, so it cannot be spread.

  3. 3

    Fix the new object used as a key

    easy8 min

    A fresh object is a different key, so nothing is found.

  4. 4

    Fix WeakSet used with a primitive

    easy8 min

    A WeakSet holds objects only.

  5. 5

    Fix the Map chosen where a WeakMap fits

    easy8 min

    A normal Map keeps its keys alive, which is the leak being avoided.

Ready to write the code?

The editor, the automatic checks and the worked solutions open up with an account.

Open the workspace