DEV Community

K
K

Posted on

JavaScript Symbolism

With ES2015 JavaScript got a rather huge update that brought many new things to lift it to a more modern place. One of these additions are symbols.

What

Symbol is a new basic type in JavaScript that has one main purpose: being unique

While objects are unique too, Symbols have the advantage of being usable as object keys.

How

There is a global function called Symbol() that returns a new unique symbol every time it's called.

const mySymbol = Symbol();
const anotherSymbol = Symbol();

mySymbol === anotherSymbol // -> false
Enter fullscreen mode Exit fullscreen mode

With Description

We can also add an description, to distinguish them later:

const mySymbol = Symbol("xyz");

console.log(mySymbol); // -> symbol(xyz)
Enter fullscreen mode Exit fullscreen mode

Be warned, this allows a symbol to be fetched via Symbol.for("xyz"). If we want to use a unique key nobody can override, this can be a problem.

Also, every call to Symbol() results in an unique symbol, even if we use the same description.

Well Know Symbols

There are also pre-defined symbols, called well known symbols.

They are used by JavaScript to determine object behavior without interfering with our string keys.

There is Symbol.iterator for example, this is used to mark the iterator method of an Array so it can be used in a for-loop.

const myObject = {
  [Symbol.iterator] = function*() {
    yield "first value";
    yield "second value";
  }
};

for(let value of myObject) console.log(value);
Enter fullscreen mode Exit fullscreen mode

Here we add a generator function to our object inside the Symbol.iterator key, this allows myObject to be used with a for-loop.

Why

One use-case is to add keys to objects only the creator of a symbol knows about.

React, for example, marks objects created with the React.createElement() function with a custom symbol, so it knows they are React elements later. If they would have used a string, it could be accidentally overriden.

Another use-case, as mentioned above, is the use of well known symbols to make custom objects behave more native.

Top comments (3)

Collapse
 
kepta profile image
Kushan Joshi

Great article K!
One more use case I can think of is that it allows JavaScript API to grow and avoid variable naming collision. For example I canโ€™t have a property called __proto__ in my object because old JS didnโ€™t have Symbols. But now with symbols they can introduce new things like Symbol.Iterator without resorting to weird things like __iterator__ ๐Ÿ˜….

Collapse
 
avalander profile image
Avalander

Thanks for sharing, very well explained! I never jumped into the Symbol train because I couldn't be bothered to read the documentation, but this told me everything I needed to know.

Collapse
 
audeadev profile image
Audea Development

I particularly like the disclaimer on this example. Great showcase of the feature.