Hidden Identifiers
A Symbol (Symbol) is an absolutely unique and immutable data type. Even if you create two symbols with the same description, they will be different.
let id1 = Symbol("id");
let id2 = Symbol("id");
alert(id1 === id2); // false!
Why are they needed?
- Hidden Properties: If you want to add a property to an object that won't randomly " pop up " in a
for..inloop or during JSON conversion. This is useful for third-party libraries. - System Keys: JS uses special symbols (Well-known Symbols) to change language behavior. For example,
Symbol.iteratorturns an object into an " iterable " one.
Note
Symbols are not automatically converted to strings. You cannot do alert(id1), you must call id1.toString().
Tip
There is a " Global Symbol Registry " . If you want symbols with the same name to be equal, use Symbol.for("name").