Execute Program

Modern JavaScript: Builtin Symbols

Welcome to the Builtin Symbols lesson!

This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!

  • JavaScript defines several symbols for us. These are used for metaprogramming, which means "changing the behavior of a program using code". Using these built-in symbols, we can modify how JavaScript runs our code. Here's one example:

  • By default, calling .toString() on an object results in the string '[object Object]'.

  • >
    const anObject = {};
    anObject.toString();
    Result:
  • It doesn't matter what the object contains; it always returns '[object Object]'.

  • >
    const user = {name: 'Dalili'};
    user.toString();
    Result:
    '[object Object]'Pass Icon
  • Why is the string '[object Object]'? The first "object" tells us that this is a string representation of an object. The second, capitalized "Object" refers to the object "tag", which we can customize.

  • When we call .toString() on an object, the JavaScript runtime looks for a property on that object named Symbol.toStringTag. If that property exists, the runtime replaces the "Object" tag in '[object Object]' with the property.

  • >
    const anObject = {};
    anObject[Symbol.toStringTag] = 'myObject';
    anObject.toString();
    Result:
  • We can assign Symbol.toStringTag on an existing object (like above) or we can define it when the object is first defined (like below).

  • >
    const user = {
    name: 'Amir',
    [Symbol.toStringTag]: 'Amir'
    };
    user.toString();
    Result:
    '[object Amir]'Pass Icon
  • There are more built-in symbols beyond this simple toStringTag example. In a future lesson, we'll use a built-in symbol to customize for-of loop iteration, allowing regular loops to iterate over our own custom objects as if they were arrays.