EasyModern JS📖 Theory Question

What are Symbols and what are their main use cases?

💡

Hint

Unique, non-string property keys — used for collision-free metadata and well-known protocols

Full Answer

A Symbol is a primitive that is guaranteed globally unique. Used mainly as object property keys to avoid name collisions.

const id = Symbol('id');
const id2 = Symbol('id');
id === id2; // false — always unique even with same description

const user = {};
user[id] = 42; // Symbol as property key

// Symbols are invisible to normal enumeration
Object.keys(user);                          // []
JSON.stringify(user);                       // '{}' — symbols excluded
Object.getOwnPropertySymbols(user);         // [Symbol(id)] — explicit access

// Well-known Symbols — customize built-in behavior
class MyIterable {
  [Symbol.iterator]() {      // makes instances work in for...of
    let n = 0;
    return { next: () => n < 3
      ? { value: n++, done: false }
      : { done: true } };
  }
}

for (const v of new MyIterable()) console.log(v); // 0, 1, 2

// Other well-known Symbols:
// Symbol.toPrimitive — control type coercion
// Symbol.hasInstance — customize instanceof
// Symbol.toStringTag — customize Object.prototype.toString output
💡 Use Symbols as property keys when extending objects you don't own — impossible to accidentally collide with existing or future string keys.

More Modern JS Questions

MediumWhat are generators and when would you use them?→EasyWhat is optional chaining (?.) and nullish coalescing (??)?→EasyWhat are tagged template literals and what are they used for?→EasyExplain destructuring for objects and arrays — including defaults, renaming, rest, and nesting.→

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint