Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. JavaScript
  3. Reference
  4. Standard built-in objects
  5. Symbol
  6. for()

Symbol.for()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨September 2015⁩.

TheSymbol.for() static method searches for existing symbolsin a runtime-wide symbol registry with the given key and returns it if found. Otherwisea new symbol gets created in the global symbol registry with this key.

Try it

console.log(Symbol.for("bar") === Symbol.for("bar"));// Expected output: trueconsole.log(Symbol("bar") === Symbol("bar"));// Expected output: falseconst symbol1 = Symbol.for("foo");console.log(symbol1.toString());// Expected output: "Symbol(foo)"

Syntax

js
Symbol.for(key)

Parameters

key

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

Return value

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

Description

In contrast toSymbol(), theSymbol.for() function creates asymbol available in aglobal symbol registry list.Symbol.for() does alsonot necessarily create a new symbol on every call, but checks first if a symbol with thegivenkey is already present in the registry. In that case, that symbol isreturned. If no symbol with the given key is found,Symbol.for() willcreate a new global symbol.

Examples

Using Symbol.for()

js
Symbol.for("foo"); // create a new global symbolSymbol.for("foo"); // retrieve the already created symbol// Same global symbol, but not locallySymbol.for("bar") === Symbol.for("bar"); // trueSymbol("bar") === Symbol("bar"); // false// The key is also used as the descriptionconst sym = Symbol.for("mario");sym.toString(); // "Symbol(mario)"

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

js
Symbol.for("mdn.foo");Symbol.for("mdn.bar");

Specifications

Specification
ECMAScript® 2026 Language Specification
# sec-symbol.for

Browser compatibility

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp