Skip to content

Latest commit

 

History

History
39 lines (25 loc) · 1.21 KB

File metadata and controls

39 lines (25 loc) · 1.21 KB

69. Weak collections and object lifetime

Learn

  • WeakMap
  • WeakSet
  • object identity
  • garbage collection

How it works

WeakMap keys and WeakSet values are objects held weakly, so the collection does not keep those objects alive by itself. These collections are not enumerable because their contents can change as garbage collection runs. Use them for private metadata or membership tracking tied to object lifetime.

Common mistake

Do not use WeakMap when you need to list, serialize, or count all entries.

Guided challenge

Store private metadata for DOM elements in a WeakMap and compare it with an ordinary Map. Explain why garbage collection cannot be demonstrated deterministically.

Further reading

Run the example

Open example.html, inspect example.js, then edit and refresh. For APIs that need an origin, run a local server from the JavaScripts folder.

Completion check

  • Explain the behavior and its limits in your own words.
  • Test a normal case and a failure or cleanup case.
  • Record when this feature is useful and when a simpler approach is better.