Chapter III · Data Types

Symbol

Symbol is a primitive type used to create entirely unique and collision-free identifiers for object properties.

01 What is a Symbol?

Introduced in ES6, a Symbol is a primitive whose values are guaranteed to be unique. Even if two symbols share the exact same description string, they are completely distinct from one another.

Symbols are primarily used to create hidden or collision-resistant object properties that won't interfere with standard string-keyed properties or enumeration loops.

02 Simple Example

Creating unique symbols and using them as private object keys.

symbol.js
const ID = Symbol("id");
const user = {
  name: "Alice",
  [ID]: 12345
};

console.log(user[ID]); // 12345
console.log(Object.keys(user)); // ["name"] (Symbol key is hidden!)

Symbol keys are omitted from standard for...in loops and Object.keys(), providing lightweight property encapsulation.

03 How It Works

Every call to Symbol() allocates a brand new, immutable primitive identifier in memory that cannot clash with any other key.

Variable Reference Primitive Value

Symbols generate unique primitive tokens that serve as hidden property keys.

04 Step-by-Step

  1. Calling Symbol("description") generates a unique primitive token.

  2. The symbol is assigned as a property key on an object using computed property brackets [key].

  3. Access requires referencing the exact same symbol variable reference.

05 Mental Model

"A tamper-proof serial number stamped on a specific part inside a machine."

No other part in the entire factory shares that exact serial number, preventing mix-ups.

06 Interview Questions

Q: Are Symbol keys enumerable in a for...in loop or Object.keys()?

No — they're intentionally excluded from both, which is what makes them useful for adding metadata to an object without colliding with or exposing regular properties.

Q: Does Symbol('id') === Symbol('id')?

No — every call to Symbol() creates a unique value regardless of the description string passed in.

Key Takeaway

Symbols provide unique, collision-proof primitive identifiers ideal for creating hidden or special-purpose object properties.

Related Concepts