Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Symbol() and Symbol.for()

Tags:

ecmascript-6

I try to create object with Symbol key and find corresponding value with Symbol.for, but it doesn't work:

const sym = Symbol("x");

let obj = {
  [sym]: "val"
}

console.log(obj[sym]); // "val"
console.log(obj[Symbol.for("x")]); // undefined, but expected "val"

Why?

like image 444
mqklin Avatar asked Jan 04 '16 09:01

mqklin


2 Answers

Symbols created using Symbol() are unique and immutable, so the only way you can reference it is by assigning it to a variable.

It's important to note that the constructor param is actually a description of the symbol, not a key. From MDN:

A description of the symbol which can be used for debugging but not to access the symbol itself

(emphasis mine)

Symbol.for on the other hand stores Symbols in a global registry list using the specified key, so for your example to work you need to both create and access the symbol using Symbol.for:

const sym = Symbol.for("x"); // Create a symbol in the global registry

let obj = {
  [sym]: "val"
}

console.log(obj[Symbol.for("x")]); // Access the symbol from the global registry
like image 93
CodingIntrigue Avatar answered Oct 27 '22 13:10

CodingIntrigue


That is not how Symbol.for works.

If you create a new Symbol using the Symbol function, you will get a unique symbol every time. Example:

const sym1 = Symbol("x");
const sym2 = Symbol("x");
sym1 === sym2; // returns false

If you want to use a global symbol, you will have to define it using Symbol.for as well:

const sym = Symbol.for("x");

let obj = {
  [sym]: "val"
}

console.log(obj[Symbol.for("x")]); // undefined, but expected "val"
like image 35
nils Avatar answered Oct 27 '22 12:10

nils