Symbols and Well-Known Symbols
Build a precise mental model of JavaScript values, scope, functions, objects, arrays and asynchronous behavior, then implement and debug real utilities from first principles instead of memorizing outputs.
What you will be able to do
#- Create unique property keys with Symbol and explain their purpose.
- Use Symbol.for to share a symbol across modules.
- Customize built-in behavior with well-known symbols.
Overview
#Unique keys
A Symbol is a primitive that is guaranteed to be unique. Every call to Symbol() returns a new value, even with the same description. Symbols are most useful as property keys that cannot collide with string keys, which is how libraries add hidden metadata without breaking user objects.
const id = Symbol('id');
const other = Symbol('id');
console.log(id === other); // false
console.log(typeof id); // symbol
The global registry
Symbol.for looks up a symbol in a shared registry by string key, so two modules that call Symbol.for('app.id') get the same symbol. Symbols are not enumerable in for..in or Object.keys, but they are copied by Object.assign and spread and are visible to Object.getOwnPropertySymbols.
Well-known symbols
The language uses built-in symbols to hook into internal operations. Symbol.iterator makes an object iterable, Symbol.toPrimitive controls coercion, Symbol.toStringTag changes the tag in Object.prototype.toString, and Symbol.hasInstance customizes instanceof. Implementing these lets your objects behave like built-ins.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
What does this line print?
Read the code, then choose the best answer. The reference explanation stays hidden until you respond. stimulus.javascriptconst a = Symbol('x'); const b = Symbol.for('x'); const c = Symbol.for('x'); console.log(a === b, b === c, typeof a);Exercise 2Explain
Explain why a library might use a Symbol as a property key instead of a string.
starter.textconst internal = Symbol('internal'); obj[internal] = true;Reveal the reference answer
reference.textA string key can collide with a key the application already uses, which would silently overwrite data. A symbol is unique, so the library's key cannot clash. Symbol keys are also skipped by for..in, Object.keys and JSON.stringify, so the metadata stays out of the object's public shape while still being reachable through Object.getOwnPropertySymbols.Authored expected output: true
The answer should name collision avoidance and non-enumerability as the two reasons, and should note the escape hatch for reflection.
Exercise 3Implement
Implement a `money` object with Symbol.toPrimitive so that `console.log(money + 0, \`\${money}\`)` prints `5 $5`.
starter.javascriptconst money = { amount: 5, // your code here };Reveal the reference answer
reference.javascriptconst money = { amount: 5, [Symbol.toPrimitive](hint) { return hint === 'string' ? '\$' + this.amount : this.amount; } };Authored expected output: 5 $5
Symbol.toPrimitive receives a hint of 'number', 'string' or 'default' and returns the primitive. Returning the number for numeric contexts and a formatted string for string contexts gives both results.
Exercise 4Debug
This object is meant to be iterable but for..of throws. Find and fix the bug.
starter.javascriptconst range = { from: 1, to: 3, iterator() { let current = this.from; const to = this.to; return { next: () => current <= to ? { value: current++, done: false } : { value: undefined, done: true } }; } }; for (const n of range) console.log(n);Reveal the reference answer
reference.javascriptconst range = { from: 1, to: 3, [Symbol.iterator]() { let current = this.from; const to = this.to; return { next: () => current <= to ? { value: current++, done: false } : { value: undefined, done: true } }; } }; for (const n of range) console.log(n);Authored expected output: 1 2 3
for..of looks for the well-known Symbol.iterator method, not a method named iterator. Naming the method with the symbol makes the object iterable.
Exercise 5Test
Write assertions that prove symbol keys are hidden from Object.keys but visible to Object.getOwnPropertySymbols.
starter.javascriptfunction assertEqual(actual, expected, label) { if (JSON.stringify(actual) !== JSON.stringify(expected)) throw new Error(label + ': unexpected value'); }Reveal the reference answer
reference.javascriptconst secret = Symbol('secret'); const obj = { visible: 1, [secret]: 2 }; assertEqual(Object.keys(obj), ['visible'], 'symbol key is not enumerable as a string'); assertEqual(Object.getOwnPropertySymbols(obj).length, 1, 'symbol key is discoverable'); assertEqual(obj[secret], 2, 'symbol key still reads'); console.log('all assertions passed');Authored expected output: all assertions passed
Object.keys lists only string keys. Symbols are a separate namespace, reachable through getOwnPropertySymbols and by the symbol reference itself.
Exercise 6Interview
How would you make a custom collection class work with for..of and the spread operator?
Reveal the reference answer
reference.textI implement a method keyed by Symbol.iterator that returns an iterator with a next method. Once that exists, for..of, spread, Array.from and destructuring all work because they share the same protocol. I can return a generator from the method to keep the code short, and I document the iteration order as part of the class contract.The answer should name Symbol.iterator, the iterator protocol with next, and the consumers that rely on it.
Common misconceptions
#- Two symbols with the same description are equal.
- Symbol-keyed properties appear in JSON.stringify output.
- Well-known symbols are only for library authors and never for application code.
Follow-up practice
#- javascript-foundations-metaprogramming
- javascript-foundations-property-accessors-and-descriptors
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.