To create a new primitive Symbol, you write Symbol()
with an optional string as its description:
const sym1 = Symbol();
const sym2 = Symbol("foo");
const sym3 = Symbol("foo");
The above code creates three new Symbols. Note that Symbol("foo")
does not coerce the string "foo"
into a Symbol. It creates a new Symbol each time:
Symbol("foo") === Symbol("foo"); / false
The following syntax with the TypeError
:
const sym = new Symbol(); / TypeError
This prevents authors from creating an explicit Symbol
wrapper object instead of a new Symbol value and might be surprising as creating explicit wrapper objects around primitive data types is generally possible (for example, new Boolean
, new String
and new Number
).
If you really want to create a Symbol
wrapper object, you can use the Object()
function:
const sym = Symbol("foo");
typeof sym; / "symbol"
const symObj = Object(sym);
typeof symObj; / "object"
Because symbols are the only primitive data type that has reference identity (that is, you cannot create the same symbol twice), they behave like objects in some way. For example, they are garbage collectable and can therefore be stored in FinalizationRegistry
objects.