Use an object as a WeakMap key and read the value back.
Acceptance criteria
- 1.#out should show cached.
JavaScript Tutorial · JavaScript Map & Set
These 10 tasks go with the JavaScript WeakMap and WeakSet 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: “WeakMap and WeakSet hold objects without preventing them being cleaned up.” .
1.Store against an objectexercise · easy · 10 min
Use an object as a WeakMap key and read the value back.
Passes when: #out should show cached.
2.Check for a keyexercise · easy · 10 min · practice plan
Report whether the object is in the WeakMap.
Passes when: #out should show present.
3.Reject a string keyexercise · easy · 10 min · practice plan
Catch the error when a string is used as a key.
Passes when: #out should show keys must be objects.
4.Show there is no sizeexercise · easy · 10 min · practice plan
Report that a WeakMap has no size property.
Passes when: #out should show no size property.
5.Use a WeakSetexercise · medium · 10 min · practice plan
Add an object and check a different one is not present.
Passes when: #out should show different object.
6.Fix the primitive keybug fix · easy · 8 min
A WeakMap key must be an object.
Passes when: #out should show cached.
7.Fix the attempt to loopbug fix · easy · 8 min · practice plan
A WeakMap is not iterable, so it cannot be spread.
Passes when: #out should show not iterable.
8.Fix the new object used as a keybug fix · easy · 8 min · practice plan
A fresh object is a different key, so nothing is found.
Passes when: #out should show cached.
9.Fix WeakSet used with a primitivebug fix · easy · 8 min · practice plan
A WeakSet holds objects only.
Passes when: #out should show added an object.
10.Fix the Map chosen where a WeakMap fitsbug fix · easy · 8 min · practice plan
A normal Map keeps its keys alive, which is the leak being avoided.
Passes when: #out should show weak.
Between them these tasks cover WeakMap, WeakSet and Object keys.
Looking for a different chapter? See every practice set, or switch to the interview theory questions.