Symbol(); // symbol
console.log(Symbol()); // prints "Symbol()" to the console
assert(typeof Symbol() === 'symbol')
new Symbol(); // TypeError: Symbol is not a constructor
Why Symbols?
let sym1 = Symbol()
let sym2 = Symbol('foo')
let sym3 = Symbol('foo')
Symbol('foo') === Symbol('foo') // false
Global Symbol Registry
You ask the registry for a symbol via Symbol.for() and retrieve the string associated with a symbol (its key) via Symbol.keyFor():
> const sym = Symbol.for('Hello everybody!');
> Symbol.keyFor(sym)
'Hello everybody!'
Characteristics of Symbols
Well-Known Symbols
The global object Symbol has several properties that serve as constants for so-called well-known symbols. These symbols let you configure how ES6 treats an object, by using them as property keys.
class MyClass {
static [Symbol.hasInstance](lho) {
return Array.isArray(lho);
}
}
assert([] instanceof MyClass);
class MyMatcher {
constructor(value) {
this.value = value;
}
[Symbol.match](string) {
var index = string.indexOf(this.value);
if (index === -1) {
return null;
}
return [this.value];
}
}
var fooMatcher = 'foobar'.match(new MyMatcher('foo'));
var barMatcher = 'foobar'.match(new MyMatcher('bar'));
assert.deepEqual(fooMatcher, ['foo']);
assert.deepEqual(barMatcher, ['bar']);