Symbol

A Symbol primitive is used to represent an entirely unique value. Symbols are created via invoking the Symbol function, like so:

const totallyUniqueKey = Symbol();

You can optionally pass an initial argument to this function to annotate your symbol for your own debugging purposes, but this is not necessary:

const totallyUniqueKey = Symbol('My Special Key');

Symbols are used to act as property keys where uniqueness is required or where you want to store metadata on objects. When you add a property to an object with a Symbol key, it will not be iterated over by normal object iteration approaches (such as for...in). Symbol keys of an object can only be retrieved via Object.getOwnPropertySymbols:

const thing = {};
thing.name = 'James';
thing.hobby = 'Kayaking';
thing[Symbol(999)] = 'Something else entirely';

for (let key in thing) console.log(key);
// => "name"
// => "hobby"

const symbols =
Object.getOwnPropertySymbols(thing); // => [Symbol(999)]

thing[symbols[0]]; // => "Something else entirely"

Since Symbol keys exist in an explicit but hidden manner, they are useful for storing programmatic information semantically that's unrelated to the core data of the object but useful in fulfilling some programmatic need. For example, you may have a logging library and wish to annotate specific objects with custom-rendering functions that log in a specific way. Such a need could be easily fulfilled with symbols:

const log = thing => {
console.log(
thing[log.CUSTOM_RENDER] ?
thing[log.CUSTOM_RENDER](thing) :
thing
);
};
log.CUSTOM_RENDER = Symbol();

class Person {
constructor(name) {
this.name = name;
this[log.CUSTOM_RENDER] = () => {
return `Person (name = ${this.name})`;
};
}
}

log(123); // => Logs "123"
log(new Person('Sarah')); // => Logs: "Person (name = Sarah)"
log(new Person('Wally')); // => Logs: "Person (name = Wally)"
log(new Person('Julie')); // => Logs: "Person (name = Julie)"

There are not many everyday situations that would necessitate the creation and usage of new symbols, but there are many instances of prescribing native behavior by such symbols. For example, you can define a custom iterator for your object by using the Symbol.iterator property. We will cover this in greater detail in the Arrays and iterables section, later in this chapter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.67.251