🔑

How to Use Symbol in JavaScript

JavaScriptAdvanced

Create unique identifiers with Symbol.

Code Example

JavaScript
// Create symbols
const sym1 = Symbol();
const sym2 = Symbol("description");
const sym3 = Symbol("description");

console.log(sym2 === sym3); // false (always unique)
console.log(typeof sym1); // "symbol"

// Use as object property
const id = Symbol("id");
const user = {
  [id]: 123,
  name: "Alice"
};

console.log(user[id]); // 123
console.log(Object.keys(user)); // ["name"] (symbols not enumerable)

// Symbol.for - global registry
const globalSym1 = Symbol.for("app.id");
const globalSym2 = Symbol.for("app.id");
console.log(globalSym1 === globalSym2); // true

// Well-known symbols
const iterable = {
  [Symbol.iterator]() {
    let i = 0;
    return {
      next: () => {
        return i < 3 
          ? { value: i++, done: false }
          : { done: true };
      }
    };
  }
};

for (const val of iterable) {
  console.log(val); // 0, 1, 2
}

// Symbol.toPrimitive
const obj = {
  [Symbol.toPrimitive](hint) {
    if (hint === "number") return 42;
    if (hint === "string") return "forty-two";
    return true;
  }
};

console.log(+obj); // 42
console.log(`${obj}`); // "forty-two"

// Symbol.hasInstance
class EvenNumber {
  static [Symbol.hasInstance](value) {
    return typeof value === "number" && value % 2 === 0;
  }
}

console.log(4 instanceof EvenNumber); // true
console.log(3 instanceof EvenNumber); // false

// Private properties with Symbol
const _name = Symbol("name");
const _age = Symbol("age");

class Person {
  constructor(name, age) {
    this[_name] = name;
    this[_age] = age;
  }
  
  getName() { return this[_name]; }
  getAge() { return this[_age]; }
}

const person = new Person("Bob", 30);
console.log(person.getName()); // "Bob"
console.log(Object.keys(person)); // [] (symbols hidden)

Explanation

Symbol creates unique identifiers. Use as property keys for hidden data. Symbol.for() for global registry. Well-known symbols customize object behavior (iterator, toPrimitive, etc).

Related Tutorials