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 object
s are unique too, Symbol
s 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
With Description
We can also add an description, to distinguish them later:
const mySymbol = Symbol("xyz");
console.log(mySymbol); // -> symbol(xyz)
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);
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)
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__
๐ .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.I particularly like the disclaimer on this example. Great showcase of the feature.