Question

There are six primitive data types in JavaScript:

Boolean, Number, String, Symbol, undefined, null

A WeakMap can't have primitive data types as keys. And a WeakSet can't have primitive values.

Why is this? Is it a language design decision (in which case, what drove this?) or is there a fundamental reason why primitives can't be stored weakly? I feel like it's probably the latter but I'm not sure why.

Was it helpful?

Solution

Because implementations of the language are likely to use primitive types as value types rather than reference types. That is, when you assign a value to a new variable, rather than changing the variable such that a contains a reference to the same object used in the source expression, it might copy the value of that object into the variable (if you know C#, think about the different between a struct and a class). Such a value therefore could not sensibly be used as part of a weak referenced storage system, as there is no object to be garbage collected (just values that get copied around) and therefore the weak key removal would never trigger.

The use of values rather than references for these common data types is an optimisation that can produce substantial performance improvements, and therefore the developers of ECMAscript would have been careful to avoid adding any features that mean it couldn't be used.

If you need to use such an item, you can simply create a container object (usually called a "box") to keep the value and allow it to be used in contexts where only references are permitted.

Licensed under: CC-BY-SA with attribution
scroll top