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?

  1. Hidden Properties: If you want to add a property to an object that won't randomly " pop up " in a for..in loop or during JSON conversion. This is useful for third-party libraries.
  2. System Keys: JS uses special symbols (Well-known Symbols) to change language behavior. For example, Symbol.iterator turns 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").