What are Symbols in JavaScript

· Category: JavaScript

Short answer

A Symbol is a unique, immutable primitive value often used as an object property key to avoid name collisions and create pseudo-private properties.

How it works

Every call to Symbol() produces a unique value, even with the same description:

const a = Symbol("id");
const b = Symbol("id");
console.log(a === b); // false

Example

const id = Symbol("id");
const user = { name: "Lia", [id]: 42 };
console.log(user[id]); // 42
console.log(Object.keys(user)); // ["name"] (Symbol keys are hidden)
console.log(Object.getOwnPropertySymbols(user)); // [Symbol(id)]

Why it matters

Symbols let libraries add metadata to objects without polluting enumerability. Well-known symbols like Symbol.iterator and Symbol.toStringTag customize built-in behavior.

Common issues

  • Symbols are not coerced to strings automatically; use .toString() if needed.
  • JSON.stringify ignores Symbol-keyed properties.