In Part I we looked at the Symbol constructor and general use cases. In this second episode, we'll explore the 2 static Symbol methods, Symbol.for()
and Symbol.keyFor()
. Don't worry, we'll finally get to the (in)famous Symbol.iterator
in due time.
These 2 methods are known as "static" methods because they can only be called from the class itself and cannot be accessed via an instance of a class:
class myClass {
static greeting() {
console.log('Hello world!');
}
}
myClass.greeting() // Logs "Hello world!"
const foo = new myClass();
foo.greeting(); // Logs a TypeError
With that out of the way, let's look at Symbol.for()
. The syntax for this method is:
Symbol.for(key); // The key is a string that identifies the symbol
While Symbol()
always creates a brand new, totally unique value, Symbol.for()
will do one of 2 things:
1) If there is no symbol created with the given key, a new symbol is created. 2) Otherwise the method will return the existing symbol with the provided key.
Symbol.for('abc'); // Create a new symbol w/ "abc" as the key
Symbol.for('abc'); // Retrieve existing "abc" symbol
Although this looks similar to Symbol()
, Symbol.for()
's argument functions as both the key to search for (or create) and the description:
const weaponSymbol1 = Symbol.for('knife');
const weaponSymbol2 = Symbol('club');
console.log(weaponSymbol1.description); // "knife"
console.log(weaponSymbol2.description); // "club"
This is an important distinction as Symbol()
's argument is only a description:
const s1 = Symbol('abc'); // Create unique symbol
const s2 = Symbol.for('abc'); // No symbol with "abc" key so create one
s1 === s2; // false
s2 === Symbol.for('abc'); // true
Moving on to Symbol.keyFor()
, this one is more straightforward as it simply returns the key of a provided symbol as a string:
const weaponSymbol = Symbol.for('sword');
Symbol.keyFor(weaponSymbol); // "sword"
Note that Symbol.keyFor()
only looks for symbols created with a key created via Symbol.for()
and the descriptions you create with Symbol()
do not provide a searchable key:
const weaponSymbol = Symbol('sword');
Symbol.keyFor(weaponSymbol); // undefined
So that's Symbol.for()
and Symbol.keyFor()
. These methods give you greater flexibility in determining just how "unique" you want your symbols to be (with plain Symbol()
being the most unique). We'll take a look at some of Symbol's static properties in the next article. Betcha can't wait! ๐
Check out more #JSBits at my blog, jsbits-yo.com. Or follow me on Twitter!