🟨 JavaScript Intermediate

What are Symbols in JavaScript?

Answer

Symbol (ES6) is a primitive type that creates unique, immutable identifiers — no two symbols are ever equal, even with the same description. Create: const id = Symbol("description"). The description is for debugging only. Use as object property keys to avoid name collisions with other code: const KEY = Symbol("key"); obj[KEY] = value. Symbols are not enumerated by for...in, Object.keys(), or JSON.stringify() — making them effectively private. Object.getOwnPropertySymbols(obj) retrieves symbol keys. Well-known Symbols customize built-in behavior: Symbol.iterator (makes objects iterable), Symbol.toPrimitive (custom type conversion), Symbol.hasInstance (custom instanceof), Symbol.toStringTag (custom toString tag). Global Symbol registry: Symbol.for("key") creates/retrieves a shared symbol — same key = same symbol globally.