Symbols are a new primitive type in ES6. If you ask me, they’re an awful lot like strings. They are tokens that serve as unique IDs. They will help avoid name clashes between properties.
Why Symbols?
There are two key points to understand about symbols:
- A symbol is unique and immutable.
- You can use symbols as identifiers when adding properties to an object.
Symbols are not private
Symbols are not private after all, because you can find them via reflection. Specifically, via the Object.getOwnPropertySymbols
method and through proxies.
The Symbol Function
Let’s start by creating a new symbol. Creating a new symbol is as easy as invoking Symbol as a function.
var secret = Symbol();
Note that there's no new
. The new
operator will throw an error if you tried to use it.
For debugging purposes, you can give a description to the symbol:
var secret = Symbol('this is a description for the secret');
Symbols are immutable
like numbers or strings. But they are unique, unlike numbers and strings.
var s1 = Symbol();
var s2 = Symbol();
s1 === s2; // false
Symbols as keys
You can use symbols as keys into an object. In the following code we create one property using a string ("lastName"), and one with a symbol (the firstName symbol).
var firstName = Symbol();
var person = {
lastName: "A",
[firstName]: "Sean",
};
This will help us to create unique keys, where in an object, keys cannot be duplicated.
etrieving Symbols
Keys created using symbols, are not going to appear when using Object.getOwnPropertyNames
, for..in
loops, or JSON.stringify
. You will have to use getOwnPropertySymbols
instead.
Retrieving Symbols
Let's look at an example where symbols are being retrieved using Object.getOwnPropertyNames
:
var firstName = Symbol();
var person = {
lastName: "A",
[firstName]: "Sean",
};
var symbol0 = Object.getOwnPropertySymbols(person)[0];
@@iterator
You can use symbols to make new iterable objects.
The iterator property attached to the Symbol function is what’s called a well-known
symbol. The following code will check to see if strings, arrays, and numbers are iterable by looking for this well-known iterator method.
var sum = 0;
vr numbers = [1,2,3,4];
for(let n of numbers) {
sum += n;
}
sum === 10; // true
The for..of
is an iterator method. Let's have a look what really happens behind the scenes:
...
let iterator = numbers[Symbol.iterator]();
let next = iterator.next();
...