I bet you don’t know JS Symbols

Shonn Lyga
PoZeCode
Published in
2 min readApr 26, 2020

Important Takeaway

There are Local and Global Symbols, and they are not the same even for similar keys.

Photo by Goran Ivos on Unsplash

Opening Fluff (you can skip this part)

The world-wide isolation will soon be over, and we will be back in our offices, back to coffee and water-cooler small talk conversations. They’ll all be asking “so, what did you learn during this time?”. Do you want to be caught off-guard? No? Then ask them about Javascript Symbols. With a high-degree of certainty they won’t be challenging you after this for at least a year.

Javascript Symbols

A Symbol in Javascript (starting with ES2015/ES6) is a relatively new primitive type, similar to string, integer and couple others. There are 2 types of Symbols that differ in scope — Local and Global. See below.

Here are some interesting Characteristics of Symbols:

When using Symbols as object prop keys, that prop won’t be enumerable:

Symbol(‘str’) creates a local Symbol.
Symbol.for(‘str’) creates a Global Symbol for the whole runtime (including iFrames):

If Global Symbol does not exists, it will be automatically created:

Some of Javascript’s functionality is powered by Symbols that are predefined. For example, what if you want to create a spreadable object? Well, using a predefined Global Symbol of course:

Changing object property with local Symbol key creates another object property (kind of immutable):

Changing object property with Global Symbol key will override the property:

Global Symbols != local Symbols:

If you try to get a non-existing Symbol from Global registry, it will create one for you:

Creating local Symbols for similar string values, creates unique Symbols:

Creating Symbols without any arguments will still create unique Symbols:

You can’t alert() a Symbol (it won’t automatically convert to string)

Shonn

--

--