WeakMap and WeakSet
In short: JavaScript frees memory automatically — once nothing in the
program can reach an object any more, the garbage collector may remove it.
A normal Map or Set counts as a reference, so anything stored in one can
never be collected, even after every other part of the program has let go
of it. WeakMap and WeakSet hold their objects weakly: if the only
thing still pointing at an object is a weak collection, the object — and
its entry — can vanish. In exchange, their keys must be objects, and
neither collection can be looped over or asked for its size, since entries
may disappear at any moment.

Attach a note to a song object
A WeakMap works like a Map for reading and writing, but its key must be an object — here, the song itself:
This behaves exactly like a normal Map so far: get and has work the
same way. The difference only shows once nothing else references song —
at that point the object, and this entry, become eligible for collection,
something a normal Map would never allow.
Try a string as a WeakMap key
Keys must be objects, because a string or number could be recreated at any time and would never truly "go away" — weak references need something with a real, trackable lifetime:
This throws TypeError: Invalid value used as weak map key. Swap the
string for an object — new WeakMap().set({}, 1) — and it works fine.
Mark songs that have already been rendered
A WeakSet is the "mark, don't store a value" version — perfect for remembering which objects have already been processed:
This prints false then true. If song later leaves the playlist and
nothing else references it, both the object and its mark in rendered
become eligible for collection — no cleanup code required.
The need
Avoid drawing the same song object twice, without keeping removed songs in memory.
The trap: expecting Map-like listing
WeakMap and WeakSet deliberately leave out anything that would let you see every entry, because entries can vanish mid-list:
forEach is undefined — it does not exist on WeakMap at all — while
get is a real function. Only get, set, has and delete exist on
WeakMap; only add, has and delete exist on WeakSet.
Quick practice
What happens with new WeakMap().set("id", 1)?
Can you loop over the entries of a WeakMap or read its size?
A song object's only remaining reference is as a key in a WeakMap. What can happen?
Which job fits a WeakSet best?
Which of these is a WeakMap method?
🎯 Your turn
A player caches a computed waveform for each song object in a Map. Over a long session memory keeps growing even after songs are removed. Explain why, and why a WeakMap fixes it, including one limitation you accept in exchange.
Write your explanation and submit it — there's no code to run here, just your reasoning.
