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?
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
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With