0

For the below code,

let obj = {
    [Symbol('my_key')]: 1,
    enum: 2,
    nonEnum: 3
}

document.write(Symbol.keyFor(Symbol.for('my_key')) + '<br>'); //  retrieves 'my_key'
document.write(Symbol.keyFor(Object.getOwnPropertySymbols(obj)[0])); //  does not retrieve 'my_key'

below is the output:

my_key
undefined

Why Symbol.keyFor() does not retrieve token string in second case?

Ryan Cavanaugh
  • 209,514
  • 56
  • 272
  • 235
overexchange
  • 15,768
  • 30
  • 152
  • 347
  • Related: [What is 'global symbol registry'?](https://stackoverflow.com/q/31897015/1048572) and [Get the description of a ES6 Symbol](https://stackoverflow.com/q/30301728/1048572) – Bergi May 12 '18 at 16:04

1 Answers1

1

From MDN:

The Symbol.keyFor(sym) method retrieves a shared symbol key from the global symbol registry for the given symbol.

In your first case you are using global symbol but as object key using local symbol:

// local symbol
Symbol('my_key')

// global symbol
Symbol.for('my_key')

When you use global symbol in your object literal it will work as youw expect:

let obj = {
    [Symbol.for('my_key')]: 1,
    enum: 2,
    nonEnum: 3
}

Global symbols are stored in global symbol registry. How do you store local symbols is up to you. Here is demonstrated the difference between the two:

Symbol('my_key') === Symbol('my_key') // false
Symbol.for('my_key') === Symbol.for('my_key') // true
madox2
  • 49,493
  • 17
  • 99
  • 99