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
Store against an object
easy10 minUse an object as a WeakMap key and read the value back.
- 2
Check for a key
easy10 minReport whether the object is in the WeakMap.
- 3
Reject a string key
easy10 minCatch the error when a string is used as a key.
- 4
Show there is no size
easy10 minReport that a WeakMap has no size property.
- 5
Use a WeakSet
medium10 minAdd an object and check a different one is not present.
Find the bug(5)
- 1
Fix the primitive key
easy8 minA WeakMap key must be an object.
- 2
Fix the attempt to loop
easy8 minA WeakMap is not iterable, so it cannot be spread.
- 3
Fix the new object used as a key
easy8 minA fresh object is a different key, so nothing is found.
- 4
Fix WeakSet used with a primitive
easy8 minA WeakSet holds objects only.
- 5
Fix the Map chosen where a WeakMap fits
easy8 minA 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