CodeBlanks Logo Icon CodeBlanks

Well-known symbols

JavaScript course · Advanced · Lesson 68/100

Learn built-in symbols like Symbol.iterator and Symbol.toPrimitive.

Well-known symbols

JavaScript ships a set of well-known symbols on the Symbol object. These are special keys that hook into language behavior.

You have already met Symbol.iterator: it powers for...of over objects. Beyond that, Symbol.toPrimitive customizes type conversion, Symbol.toStringTag customizes toString output, and Symbol.hasInstance customizes instanceof. Each is a symbol shared across the whole runtime.

Symbol.toPrimitive

When JavaScript needs to convert an object to a primitive (for example +obj or obj + 1), it first looks for a [Symbol.toPrimitive] method.

This method receives a hint: 'number', 'string', or 'default'. You return the matching primitive value. This takes precedence over the old valueOf and toString pair and is clearer.

Exercise Label the toString output

Create a cart object. Give it an items: 3 string key and a [Symbol.toStringTag]: 'Cart' property. Log the result of Object.prototype.toString.call(cart) with console.log; the output should be [object Cart].

Show example solution
const cart = {
  items: 3,
  [Symbol.toStringTag]: 'Cart'
};
console.log(Object.prototype.toString.call(cart));

Test yourself

  1. Which symbol customizes the output of Object.prototype.toString.call(obj)?

    • Symbol.iterator
    • Symbol.toPrimitive
    • Symbol.hasInstance
    • Symbol.toStringTag
    Show answer

    Symbol.toStringTag — Correct. Symbol.toStringTag sets the label inside toString output (e.g. '[object Cart]').

  2. Define the Symbol.toPrimitive method

    const price = { value: 100, [____](hint) { return hint === 'number' ? this.value : '$' + this.value; } };
    Show answer
    const price = { value: 100, [Symbol.toPrimitive](hint) { return hint === 'number' ? this.value : '$' + this.value; } };
  3. Well-known symbols

    Symbol.iterator
    Walks with for...of
    Symbol.toPrimitive
    Customizes type conversion
    Symbol.toStringTag
    Labels toString output
    Symbol.hasInstance
    Changes instanceof behavior

All lessons in Advanced