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]'
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 namedSymbol.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.toStringTagon 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]'
There are more built-in symbols beyond this simple
toStringTagexample. 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.