Symbol.for()

The Symbol.for(key) method searches for existing symbols in a runtime-wide symbol registry with the given key and returns it if found. Otherwise a new symbol gets created in the global symbol registry with this key.

Syntax

Symbol.for(key);

Parameters

key
String, required. The key for the symbol (and also used for the description of the symbol).

Return value

An existing symbol with the given key if found; otherwise, a new symbol is created and returned.

Description

In contrast to Symbol(), the Symbol.for() function creates a symbol available in a global symbol registry list. Symbol.for() does also not necessarily create a new symbol on every call, but checks first if a symbol with the given key is already present in the registry. In that case, that symbol is returned. If no symbol with the given key is found, Symbol.for() will create a new global symbol.

Global symbol registry

The global symbol registry is a list with the following record structure and it is initialized empty:

A record in the global symbol registry
Field name Value
[[key]] A string key used to identify a symbol.
[[symbol]] A symbol that is stored globally.

Examples

Using Symbol.for

Symbol.for('foo'); // create a new global symbol
Symbol.for('foo'); // retrieve the already created symbol

// Same global symbol, but not locally
Symbol.for('bar') === Symbol.for('bar'); // true
Symbol('bar') === Symbol('bar'); // false

// The key is also used as the description
var sym = Symbol.for('mario');
sym.toString(); // "Symbol(mario)"

To avoid name clashes with your global symbol keys and other (library code) global symbols, it might be a good idea to prefix your symbols:

Symbol.for('mdn.foo');
Symbol.for('mdn.bar');

Specifications

Specification
ECMAScript (ECMA-262)
The definition of 'Symbol.for' in that specification.

Browser compatibility

DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
forChrome Full support 40Edge Full support 12Firefox Full support 36IE No support NoOpera Full support 27Safari Full support 9WebView Android Full support 40Chrome Android Full support 40Firefox Android Full support 36Opera Android Full support 27Safari iOS Full support 9Samsung Internet Android Full support 4.0nodejs Full support 0.12

Legend

Full support
Full support
No support
No support

See also