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.
Symbol.for(key);
An existing symbol with the given key if found; otherwise, a new symbol is created and returned.
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.
The global symbol registry is a list with the following record structure and it is initialized empty:
| Field name | Value |
|---|---|
| [[key]] | A string key used to identify a symbol. |
| [[symbol]] | A symbol that is stored globally. |
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');
| Specification | Status | Comment |
|---|---|---|
| ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Symbol.for' in that specification. | Standard | Initial definition. |
| ECMAScript Latest Draft (ECMA-262) The definition of 'Symbol.for' in that specification. | Draft |
| Desktop | ||||||
|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | |
| Basic support | 40 | Yes | 36 | No | Yes | 9 |
| Mobile | |||||||
|---|---|---|---|---|---|---|---|
| Android webview | Chrome for Android | Edge Mobile | Firefox for Android | Opera for Android | iOS Safari | Samsung Internet | |
| Basic support | Yes | Yes | Yes | 36 | Yes | 9 | Yes |
| Server | |
|---|---|
| Node.js | |
| Basic support | Yes |
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/for