VIEW THIS AS

Auto mode follows the Route Engine until you choose a viewpoint.

YOU ARE HERE

ROUTE CHECK

CONNECTED TO

WHAT NEXT

Use the canonical route for this room, or HELP if you are unsure.

The Gold Standard of Websites | Separating WeakMap Key Lookup from Evidence of Garbage Collection

A website removes a card, assigns null to a variable and expects its associated metadata to disappear immediately. A later inspection seems to show an empty WeakMap. Neither observation, by itself, proves that the original card object was collected.

The short answer is that WeakMap supports lookup when you already have a particular eligible key. It does not provide an enumerable inventory or a timetable for garbage collection. Explicit deletion, loss of one reference, component removal and actual collection are different events.

This guide uses original object-reference ledgers for a fictional catalogue. The executable examples check deterministic identity, lookup and deletion behaviour. They deliberately do not claim to demonstrate when a JavaScript engine reclaims an unreachable object. Platform resources and component disposal also need their own explicit lifecycle decisions.

This specialist guide belongs to the Websites root. It also connects to The Gold Standard of Education | Learning That Transfers into Life and the How X Works hub. The worked cases are original teaching examples; their numbers are stipulated so that the reasoning can be checked.

eduKateSG · Websites

Find your next learning step

Separate known-key metadata lookup from claims about collection. Trace object identity, retained references, explicit deletion and component lifetime.

ROUTE 1 · CHAPTERS 1–3

Identify the association

Compare the same object, lookalike keys, stored values and absence.

ROUTE 2 · CHAPTERS 4–6

Follow key and reference rules

Choose eligible keys and distinguish weak retention from one released variable.

ROUTE 3 · CHAPTERS 7–9

Inspect values and observations

Trace back-references, explicit deletion and empty-looking inspections.

ROUTE 4 · CHAPTERS 10–12

Design the actual lifetime

Separate component disposal, reconstructed records and cache validity.

ROUTE 5 · CHAPTERS 13–14

Check and report honestly

Verify deterministic observations without inventing a collection timetable.

Full chapter contents · Websites subject guide

Chapter contents

Identify the association · Chapters 1–3

1. Attach metadata to one particular object

2. Compare identical-looking objects with the same reference

3. Distinguish absent entries from stored undefined values

Follow key and reference rules · Chapters 4–6

4. Keep eligible key types and application identifiers separate

5. Explain what weak retention changes

6. Reassigning one variable does not remove every reference

Inspect values and observations · Chapters 7–9

7. Values can participate in the reference graph too

8. Treat explicit deletion as a deterministic operation

9. An empty-looking inspection is not an entry inventory

Design the actual lifetime · Chapters 10–12

10. Removing a component is different from disposing its work

11. Transfer the graph to reconstructed archive records

12. Choose a cache policy separately from weak retention

Check and report honestly · Chapters 13–14

13. Test deterministic behaviour without pretending to test collection time

14. Report the association and the collection claim separately

CHAPTER 1 OF 14 · Identify the association

1. Attach metadata to one particular object

Back to contents

Imagine a fictional catalogue showing a card for item R17. A program represents that card with an object containing an item code. It wants to associate a small piece of metadata with that particular object without putting the metadata directly on the card's own properties.

A WeakMap can provide that association. The program sets the card object as the key and a metadata record as the value. While it retains the same card reference, it can ask the WeakMap for that record. The item code printed inside the object is not what performs the lookup.

const card = { code: "R17" };
const metadata = new WeakMap();
metadata.set(card, { reviewed: true });
metadata.has(card); // true
metadata.get(card).reviewed; // true

Draw two separate records: the card object and the metadata record. Then draw the keyed association between them. A variable named card refers to the first object. The WeakMap lookup receives that object reference. Keeping the variable name, item code and object identity distinct prevents several later misconceptions.

The value can be another object or a primitive value. A WeakMap does not require a particular metadata schema. Our reviewed field is an application choice. It says nothing about whether the real catalogue item was reviewed, whether the review is current or whether another object representing the same item should inherit it.

The reason to consider a weakly keyed association is its retention contract, not a different notion of record equality. The map does not need to keep an otherwise unreachable key alive merely to preserve its entry. That property can suit metadata whose useful lifetime follows an object.

Begin with deterministic lookup before discussing collection. We can verify that setting this key makes this record accessible through this map. We cannot turn that verification into a claim about the future collection time of objects whose references the program may later release. Those are separate questions with different evidence.

Contents · Next chapter

CHAPTER 2 OF 14 · Identify the association

2. Compare identical-looking objects with the same reference

Back to contents

Create a second object containing the same code R17. Its visible data can match the first object's data, but it is a different object identity. Asking the WeakMap for the second object does not retrieve the first object's metadata simply because both codes have the same text.

const first = { code: "R17" };
const lookalike = { code: "R17" };
const alias = first;
const metadata = new WeakMap([[first, "reviewed"]]);
metadata.get(lookalike); // undefined
metadata.get(alias);     // "reviewed"

The alias variable is different from the first variable, but both refer to the same object. The lookalike object has matching data but a separate identity. This contrast shows why variable names and record contents are insufficient descriptions of the key.

Mutating the original object's code also does not create a new object identity. If its code changes from R17 to R18, the existing keyed association remains attached to that object unless the program explicitly changes or deletes it. Whether the old reviewed metadata is still appropriate is an application validity question.

This matters when a component is reused for a different catalogue item. A successful WeakMap lookup can return metadata associated with the component object even though its displayed record has changed. WeakMap does not inspect the code and automatically invalidate metadata when that field changes.

If the desired association is by stable item identifier across independently constructed objects, an identifier-keyed structure may better match that job. It would have its own retention and invalidation responsibilities. Do not describe object identity lookup as though it were a hidden database join on a code property.

For learner practice, give three cards: the original reference, a second reference to it and a new object with identical fields. Ask which retrieves the stored value and why. A correct answer should use identity, not the spelling of the variable or the apparent equality of printed JSON.

Contents · Previous chapter · Next chapter

CHAPTER 3 OF 14 · Identify the association

3. Distinguish absent entries from stored undefined values

Back to contents

A missing WeakMap entry and a present entry whose value is undefined can both produce undefined from get. If the application needs to distinguish them, use has with the same key. A lookup result alone does not always answer whether an association exists.

const card = {};
const other = {};
const metadata = new WeakMap([[card, undefined]]);
metadata.get(card);  // undefined
metadata.has(card);  // true
metadata.get(other); // undefined
metadata.has(other); // false

This is a deterministic distinction. No collection theory is needed to explain the two get results. One key has an explicit stored value; the other was not added. A test that reports only the two returned values throws away the observation needed to distinguish the cases.

The same care applies to false, zero and an empty string. They can be legitimate stored values. A condition that treats every falsy get result as absence can misclassify a known association. Decide whether the schema permits those values, and test presence separately when it does.

There can also be several WeakMaps using the same object key. An entry in one does not automatically exist in another. If a component creates a new metadata map during reinitialisation, a later lookup can fail despite retaining the correct object. Record the map instance as well as the key identity when diagnosing an unexpected absence.

Likewise, setting a new value for an existing key updates that association. It does not append a second separately enumerable row under the same identity. Our fixture can set reviewed true, then set reviewed false for the same key and observe the current value. The operation establishes the current association in this map, not a history of prior reviews.

Before invoking garbage collection as an explanation, inspect these ordinary alternatives: different key, different map, explicit deletion, stored undefined or replaced value. Each can produce a surprising lookup without requiring the key to have become unreachable or reclaimed. A precise ledger often resolves the issue at that simpler level.

Contents · Previous chapter · Next chapter

CHAPTER 4 OF 14 · Follow key and reference rules

4. Keep eligible key types and application identifiers separate

Back to contents

WeakMap does not accept every possible JavaScript value as a key. The current language specification permits object keys and eligible symbols; registered symbols are excluded from that weak-key eligibility. Our worked examples use ordinary objects so the identity and reference graph remain easy to inspect.

A string containing R17 is not an object reference merely because it names the same item shown on a card. Trying to set it as a WeakMap key fails under the ordinary contract. A program needing string-keyed lookup should choose a structure whose key contract includes strings rather than wrapping the text in a fresh object for every lookup.

const metadata = new WeakMap();
metadata.set("R17", { reviewed: true }); // throws TypeError

Constructing a new wrapper object for each call does not solve identity continuity. A wrapper created during set and another created during get are different objects even when both contain R17. The second wrapper cannot retrieve the first wrapper's association by matching contents.

The observation methods also have their defined handling for ineligible supplied keys. Do not assume that every method throws in the same way as set. A controlled check can establish that ordinary has, get and delete return their absence-like results for a string key, while set rejects it. These outcomes follow different method contracts.

For a practical design, decide whether the metadata belongs to a component instance, a data-record object or a stable identifier. Those are different keys even if one interface displays the same item code for all three. A component can outlive a data record, and a reconstructed data object can represent the same identifier without sharing the original identity.

The type decision should follow that intended lifetime and lookup question. WeakMap is useful when a caller naturally already has the eligible object whose metadata it needs. It does not manufacture a stable identity service from arbitrary text or decide which independently reconstructed objects should count as the same catalogue entity.

A frozen object can still be used as a key in an ordinary WeakMap. The association is not created by adding a visible metadata property to the key object. In a controlled fixture, freeze a card with its code, associate reviewed metadata through the map, and verify both that the lookup works and that no reviewed own property appeared on the card. This distinguishes external association from mutation of the represented record.

That separation can help a library keep implementation details away from an object's ordinary fields, but it should not be described as a general security boundary. Code holding the map and the key can perform the permitted lookup. Application permissions, confidentiality and user access require their actual controls. An association being absent from Object.keys on the card does not prove that no code can obtain it.

For a practical interface contract, state which part owns the metadata map and which callers receive access to the association. That is an encapsulation decision. It can coexist with frozen data records and object-identity keys without changing their meanings. The learner can check each claim separately: the key remains unchanged, the known-key lookup succeeds, and the map's availability follows the program's chosen structure. None of those observations establishes a hidden database, an authorisation system or a collection timetable.

Contents · Previous chapter · Next chapter

CHAPTER 5 OF 14 · Follow key and reference rules

5. Explain what weak retention changes

Back to contents

An ordinary Map retains its keys through its entries while the map and those entries remain reachable. A WeakMap's keyed association does not, on its own, require an otherwise unreachable eligible key to remain live. That difference concerns retention. It does not change the fact that a caller with a live key can perform an identity-based lookup.

Draw a simple reference ledger. The application has a variable pointing to a card. It also has a variable pointing to a metadata map. In the ordinary Map version, the map's entry provides another retaining route to the card. In the WeakMap version, the weak-key association is not that same independent retaining route.

This is not a claim that the card will be collected the instant the application removes its variable reference. Other retaining paths may exist, and collection is managed by the engine under its processing model. The weak association removes one reason for retention; it does not supply a visible countdown to reclamation.

The difference can matter in a long-lived website feature that associates temporary objects with derived information. If metadata is useful only while the object is otherwise available, a WeakMap can avoid turning the association itself into a permanent owner of every object ever seen.

But first check the actual data flow. If the application also stores every card in a permanent array for diagnostics, that array remains a retaining path. Choosing a WeakMap for metadata does not cancel references held by other structures. The graph must include the other structures, not just the container whose name includes “Weak”.

For learner practice, compare two stipulated graphs without predicting a collection time. In one graph, a reachable strong Map retains the card. In another, the only remaining depicted association is a weak key. Explain the retention distinction and the missing evidence about actual collection. That is a valid conceptual conclusion without pretending to measure an engine event the fixture does not expose.

Contents · Previous chapter · Next chapter

CHAPTER 6 OF 14 · Follow key and reference rules

6. Reassigning one variable does not remove every reference

Back to contents

Suppose the program creates a card and assigns an alias to it. It then sets the first variable to null. The alias still refers to the original object. Asking the WeakMap through that alias can continue to retrieve the association. The assignment changed one variable; it did not destroy the object.

let current = { code: "R17" };
const retained = current;
const metadata = new WeakMap([[current, "reviewed"]]);
current = null;
metadata.get(retained); // "reviewed"

No contradiction exists here. The object is still directly available through retained. A statement that setting current to null “deleted the weak entry” would predict the wrong result. The operation did not call delete, and it did not remove the alias.

Now add an array containing the object. Removing the current variable while leaving that array reachable still leaves a route to the card. The same reasoning applies to a closure that retains the object for a later task. The exact program determines which references remain available.

A common testing mistake is to retain the key in a helper or assertion while claiming to have released the last reference. If the test later passes the original key to has, it necessarily has some way to obtain that key at the time of the call. That lookup is not a direct observation of an object that has become inaccessible to the test.

For our deterministic fixtures, this is an advantage: retaining a key lets us verify identity, current value and explicit deletion reliably. It becomes a problem only when the report extends those checks into a claim about collection of a no-longer-accessible key.

Write each retained reference as a separate arrow in the learner's graph. Cross out only the arrow corresponding to the assignment or removal actually performed. Then ask whether another path remains. This concrete exercise builds a more accurate model than imagining the object as belonging exclusively to whichever variable was declared first.

Contents · Previous chapter · Next chapter

CHAPTER 7 OF 14 · Inspect values and observations

7. Values can participate in the reference graph too

Back to contents

A metadata value can itself be an object containing a reference back to the key. In the weak association alone, that back-reference does not automatically turn the otherwise unreachable key-value pair into a permanently retained pair. Weak-key processing must account for that relationship rather than behaving like a simple strong collection.

Now change the graph by storing the metadata value in a separate reachable array. If the value's owner field points to the card, the external array can provide a strong route through the metadata value back to the key. The WeakMap does not weaken that independently retained object property.

const card = { code: "R17" };
const detail = { owner: card, reviewed: true };
const metadata = new WeakMap([[card, detail]]);
const audit = [detail];
audit[0].owner === card; // true

This fixture does not attempt collection. It demonstrates the explicit reference route the program constructed: audit array to detail record to card. A report that draws only the WeakMap association would omit the path that matters in this changed condition.

Values can also be retained for perfectly legitimate reasons. A review history may need to preserve records after a card leaves the screen. The design question is whether the history should retain the entire component object or a smaller independent data record. That is an ownership decision, not an automatic memory defect.

For a teaching comparison, keep the metadata value the same while adding or removing the separately retained audit reference. Explain how that change alters the depicted graph. Avoid predicting an exact memory reduction or collection delay from a diagram alone. It describes references, not an engine's complete measured state.

The broader habit is to follow both keys and values. “The map is weak” is incomplete when some other reachable value points back to the key. A useful investigation names the actual retaining path and the purpose it serves, then decides whether that purpose is still required by the website's current task.

Contents · Previous chapter · Next chapter

CHAPTER 8 OF 14 · Inspect values and observations

8. Treat explicit deletion as a deterministic operation

Back to contents

If the application deliberately wants to remove an association for a known key now, it can call delete on that WeakMap. This is a deterministic entry operation. It is different from waiting for the key to become unreachable and eventually eligible for collection.

const card = {};
const detail = { reviewed: true };
const metadata = new WeakMap([[card, detail]]);
metadata.delete(card); // true
metadata.has(card);   // false
metadata.get(card);   // undefined
detail.reviewed;      // true

The metadata object remains available through detail in this fixture. Deleting the association did not destroy that object or invalidate every other reference to it. The key also remains available through card. This is why “delete the entry”, “release the key” and “free the value” should not be treated as synonyms.

A second delete of the same absent association returns false under the ordinary contract. That result describes this map's current association state. It does not prove the key object never existed, was collected or cannot be used in another map.

Deleting metadata may be an appropriate step when a component is deliberately disposed or when a derived result becomes invalid. But deleting the entry does not automatically cancel event listeners, stop timers, abort requests or close external resources. Those responsibilities require their actual lifecycle operations and ownership rules.

Likewise, deleting a weak entry is not evidence that total memory immediately decreased by the size of its value. Other references can retain the value, and engine memory management is a separate system. A reliable test asserts the association's absence and any explicitly performed lifecycle effects rather than inferring a byte-level outcome.

For practical reporting, say exactly what the application did and checked: it removed the association for the known card, then has returned false. That is a useful, defensible result. There is no need to enlarge it into an unsupported claim about destruction of all related objects or completed cleanup of the entire component.

Contents · Previous chapter · Next chapter

CHAPTER 9 OF 14 · Inspect values and observations

9. An empty-looking inspection is not an entry inventory

Back to contents

WeakMap does not expose a built-in enumerable list of keys or entries, nor a built-in size count of its keyed associations. This supports the separation between known-key lookup and observation of key liveness. An inspection that lists ordinary own properties is asking a different question.

For example, Object.keys applied to an ordinary newly created WeakMap can return an empty array even when the map has a known-key association. JSON serialization can likewise produce an empty-looking ordinary object representation. Neither operation has enumerated the WeakMap's internal associations.

const card = {};
const metadata = new WeakMap([[card, "reviewed"]]);
Object.keys(metadata); // []
JSON.stringify(metadata); // "{}"
metadata.has(card); // true

This is a strong counterexample to interpreting empty display as empty storage. The same fixture shows an empty ordinary-property enumeration and a successful known-key membership observation. Both are correct because they inspect different things.

An application can attach an ordinary property to a WeakMap object, such as a label used for debugging. That property may appear in an ordinary own-property enumeration. It does not become a keyed WeakMap entry. Similarly, assigning an ordinary property named size does not create a trustworthy count of the map's associations.

Developer tools can offer special inspection interfaces with implementation-specific displays. A screenshot of such a display needs its tool context and limitations. This article's controlled checks do not claim a universal debugger inventory or a way to monitor exact collection events through the standard WeakMap API.

If the task requires an explicit list of current members, choose or maintain a structure with that membership contract. A separate strong registry can provide it, but retaining object keys there changes the graph intentionally. Do not claim that adding a key inventory preserves precisely the same retention behaviour as having only weak associations.

Contents · Previous chapter · Next chapter

CHAPTER 10 OF 14 · Design the actual lifetime

10. Removing a component is different from disposing its work

Back to contents

A catalogue card can disappear from the visible interface while its JavaScript object remains reachable. A parent controller, pending callback, listener closure or diagnostic record may still refer to it. Visibility and document membership are useful observations, but neither is a complete reference-graph report.

The existing cloned-markup lesson explains a related identity boundary. A replacement card can look identical to the old one while having another node identity. Metadata attached to the old object does not automatically transfer to the replacement. Looking up the new object and obtaining undefined therefore does not establish that the old one was collected.

For a fictional lifecycle, record four events separately: the card is removed from its container; the controller stops accepting its actions; scheduled work is deliberately cancelled or detached under its API; and selected references are released. Those actions can be tested directly under a component contract. Actual garbage collection remains another event managed by the engine.

If metadata owns a cleanup function, invoke it according to that lifecycle when deterministic cleanup is required. Storing the function in a WeakMap does not arrange for it to run when the card disappears. A weak association is a retention property, not a disposal callback registration.

Finalization mechanisms have their own language and host constraints. They should not be assumed to deliver a prompt, guaranteed business action merely because an object becomes unreachable. A website should not make correctness of an essential user-visible operation depend on an unsupported prediction of collection timing.

Our lesson does not prescribe a universal component framework. It supplies the distinctions needed to review one: visible presence, accepted ownership, outstanding work, retained references and eventual engine collection. A correct lifecycle can remove obsolete work explicitly while using WeakMap appropriately for metadata whose retention should follow an otherwise available object. Each part should be verified through evidence suited to its actual role.

Contents · Previous chapter · Next chapter

CHAPTER 11 OF 14 · Design the actual lifetime

11. Transfer the graph to reconstructed archive records

Back to contents

The archive imports a data record for item Q42, associates derived display metadata with that object and later reconstructs the record from saved JSON. The reconstructed object can contain the same code and fields while being a different identity. A WeakMap lookup using it does not retrieve the original object's association automatically.

const original = { code: "Q42", title: "Harbour" };
const restored = JSON.parse(JSON.stringify(original));
const metadata = new WeakMap([[original, { width: 120 }]]);
metadata.has(original); // true
metadata.has(restored); // false

The absent restored-key result does not imply that JSON failed or that the original metadata vanished. It identifies a change in object identity. The import path must decide whether to recompute metadata, associate new metadata or use an identifier-based cache with an explicitly different lifetime.

Now retain the original record in an undo history. Releasing the current-view variable does not remove that history's reference. The original object can still be available for undo, and the metadata can still be found when the application obtains that same object again. This can be intended behaviour.

Change the task once more: the metadata contains a measurement made under a previous title or layout version. Reusing the same object after changing its title can make the stored width stale. WeakMap identity continuity does not establish data freshness. The application needs an invalidation or version rule that reflects what the measurement depends on.

For a transfer exercise, ask the learner to draw both the original and reconstructed objects, then add an undo-history reference and a changed title. Require separate answers about key equality, retaining paths and metadata validity. These are three different questions even though the interface still shows a single archive item.

The practical lesson is to align the association with the thing it describes. Component-instance metadata can follow component identity. Record-version metadata may need a version check. Item-level information may need an identifier. Choosing WeakMap does not decide among those meanings on the application's behalf.

Contents · Previous chapter · Next chapter

CHAPTER 12 OF 14 · Design the actual lifetime

12. Choose a cache policy separately from weak retention

Back to contents

A WeakMap can associate a derived result with an object, but weak retention is not an expiry policy. If a key remains reachable for a long time, its associated metadata can remain available. There is no built-in rule that removes a result because ten minutes passed, the catalogue changed or an external source was updated.

For a fictional title-width cache, the stored result depends on title text and layout conditions. If either changes while the same key object remains, an old result can still be returned. The application can store a version or dependency record and recompute when the required conditions differ. That is a validity rule added by the application.

Explicit expiry based on time is another policy. It needs a declared clock, interval, access behaviour and failure handling. A weak association can coexist with that policy, but it does not supply the time comparison automatically. Calling the map weak does not establish that its data is current.

The need for a complete inventory can also change the choice of structure. If an administrator must list every cached item, inspect totals or remove a selected category, a known-key-only WeakMap API may not match that management job. A strong Map or an explicitly maintained registry can be appropriate when its retention is intentional and controlled.

Do not advertise that alternative as a drop-in replacement with identical memory behaviour. Retaining keys strongly changes the graph. The design should state why those objects need to remain available and when the registry removes them. A documented owner is more useful than a container name chosen as a general promise of efficiency.

For learning, separate three columns: lookup key, validity condition and retention owner. Fill them for a temporary component measurement, an undo history and an item-level review record. A good answer can choose different structures because the jobs differ. The transferable skill is matching the container and policy to the actual question, rather than expecting one weak association to solve identity, freshness, enumeration and disposal together.

Contents · Previous chapter · Next chapter

CHAPTER 13 OF 14 · Check and report honestly

13. Test deterministic behaviour without pretending to test collection time

Back to contents

The controlled check set should establish what the standard API lets the program observe reliably. Set an object key and retrieve its value. Compare an alias with an independently constructed lookalike. Mutate a field while retaining identity, and verify that the association remains unless the application changes it.

Store undefined and distinguish it from absence using has. Update a value for an existing key. Delete a known association and check the first and second delete results, has and get. Retain the value separately to show that deletion of the association does not destroy every object involved.

Test an ineligible string key across the relevant methods, observing the defined difference between set's rejection and absence-like observation results. Keep eligible-symbol details separate from the object fixtures if the target runtime and actual feature require them. The current specification and deployed implementation should be checked together before making a compatibility claim.

Demonstrate the empty-inspection trap by comparing Object.keys and JSON output with has for a retained known key. Add an ordinary property to a fresh WeakMap object and verify that ordinary object inspection sees that property without enumerating keyed associations. This makes the representation boundary concrete.

Use reference ledgers for retention examples. An alias, strong array or externally retained metadata value can demonstrate an explicit available path. Those checks do not measure what happens after every path becomes inaccessible. Do not add a short timeout and call a passing or failing result a guaranteed garbage-collection test.

A process-specific memory experiment may be useful for an actual investigation, but it needs its runtime, instrumentation, workload and scope stated. It is different evidence from these deterministic fixtures. Our article claims only the identity, lookup, deletion and explicit-reference observations performed. Preserving that boundary makes the result more informative: a failing lookup can be diagnosed through concrete state rather than attributed prematurely to an invisible collection schedule.

Contents · Previous chapter · Next chapter

CHAPTER 14 OF 14 · Check and report honestly

14. Report the association and the collection claim separately

Back to contents

A useful report names the WeakMap instance, the exact key identity, the operation performed and the observed result. If the question concerns retention, include the relevant known reference paths and the limits of that account. If it concerns lifecycle, list the explicit stop or disposal actions separately.

For the opening misconception, the conclusion can be precise. Setting one variable to null removed one reference. An empty ordinary-property display did not enumerate the map's keyed associations. Neither observation proved that the original card was collected. A successful alias lookup or a retained history reference can explain continued access without any contradiction.

When explicit delete was performed, say so. A subsequent has result of false establishes absence of that association for the known key in that map. It does not establish destruction of the key, disappearance of separately retained metadata or completed cancellation of all component work.

For independent practice, give a learner a card, an alias, a metadata record that points back to the card and an external audit array. Remove one reference at a time and ask which routes remain. Then replace the card with an identical-looking reconstruction and ask which lookup succeeds. The learner should distinguish graph changes from data similarity.

For practical maintenance, retain small deterministic fixtures and a clear metadata lifetime. They protect against errors such as using a new wrapper key, treating stored undefined as absence or reading Object.keys as an entry count. Use actual lifecycle checks for resources that need prompt release.

The lasting habit is to keep observable association state separate from an engine's collection process. WeakMap is useful precisely because it offers a particular retention relationship without a public inventory of key liveness. Understanding that boundary lets a website attach metadata sensibly, invalidate it deliberately, dispose of work explicitly and describe its evidence without claiming a collection event it did not observe.

Contents · Previous chapter · Return to Websites

Tracing Map Visits When Entries Are Deleted and Reinserted

Tracing Map Visits When Entries Are Deleted and Reinserted. Ordinary Map membership, insertion history and traversal have their own observable contract.

Separating Object.groupBy Property Keys from Map.groupBy Key Identity

Separating Object.groupBy Property Keys from Map.groupBy Key Identity. Grouping by object key also depends on identity rather than matching fields in a new lookalike object.

Separating Cloned Markup from Registered Event Listeners

Separating Cloned Markup from Registered Event Listeners. A replacement card can look identical while carrying a different node identity and different registered behaviour.

Tracing Property Getter Effects During Structured Cloning

Tracing Property Getter Effects During Structured Cloning. A copied data record and its original are different objects, and property reads during cloning have their own effects.

Frequently asked questions

Does setting a key variable to null delete its WeakMap entry?

It changes that variable's reference. Other references can remain, and it is not an explicit delete operation or proof of collection.

Can an identical-looking object retrieve the same metadata?

Not merely by matching fields. Object keys are associated by identity; an alias of the original object is different from a newly constructed lookalike.

Does get returning undefined prove absence?

No. Undefined can be a stored value. Use has when the distinction matters.

Does Object.keys show WeakMap entries?

It inspects enumerable own object properties, not the WeakMap's keyed associations. An empty result is not proof that no association exists.

Does delete destroy the metadata object?

It removes the association for that key in that map. Other references can retain the value and the key.

Can WeakMap replace explicit component cleanup?

It does not automatically cancel work or run a disposer. Use the lifecycle operations required by the resources and component contract.

Authoritative sources and further reading

ECMAScript: WeakMap objects. Known-key associations and the lack of an enumerable key inventory.

ECMAScript: weak-reference processing model. Liveness, optional collection and the separation between reachability reasoning and collection timing.

ECMAScript: eligible weak keys. Object and eligible-symbol key conditions.

Mozilla: WeakMap. Practical identity, retention and metadata examples.

Return to the Websites subject guide, The Gold Standard of Education, or the How X Works hub.