jskatas.org Continuously Learn JavaScript. Your Way.

Symbol: Symbol.for()

Symbol.for() for registering Symbols globally.

Symbol.for for registering Symbols globally

creates a new symbol (check via typeof)
const symbolType = Symbol.for('symbol name'); assert.equal(symbolType, 'symbol');
stores the symbol in a runtime-wide registry and retrieves it from there
const sym = Symbol.for('new symbol'); const sym1 = Symbol.for('new symbol1'); assert.equal(sym, sym1);
is different to Symbol() which creates a symbol every time and does not store it
var globalSymbol = Symbol.for('new symbol'); var localSymbol = Symbol.for('new symbol'); assert.notEqual(globalSymbol, localSymbol);

.toString() on a Symbol

also contains the key given to Symbol.for()
const description = Symbol('').toString(); assert.equal(description, 'Symbol(new symbol)');

NOTE: the description of two different symbols

might be the same
const symbol1AsString = Symbol('new symbol 1').toString(); const symbol2AsString = Symbol.for('new symbol').toString(); assert.equal(symbol1AsString, symbol2AsString);
but the symbols are not the same!
const symbol1 = Symbol.for('new symbol'); const symbol2 = Symbol.for('new symbol'); assert.notEqual(symbol1, symbol2);

Related Katas


Difficulty Level


First Published

6 May 2015


6 tests to solve