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.