🟒 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