0

I recently learned about Symbols in JavaScript ES6, and I was very curious about how it is implemented underneath the hood.

Specifically, I am curious about how Symbols are implemented to achieve uniqueness:

a = Symbol('key')
b = Symbol('key')
a !== b // true

But can also achieve its for functionality:

a = Symbol.for('key')
b = Symbol.for('key')
a === b // true

Can anyone shed some light on how this is implemented underneath the hood?

I read the MDN documentation, but it mainly described the interface, rather than the implementation.

agartede
  • 21
  • 1
  • 4
    Implementation details depend on the implementation, not the language. – Quentin Dec 16 '22 at 09:32
  • Most likely the first uses a randomly generated ID or one based on the memory location, while the second uses some kind of hash of the string passed in. – mousetail Dec 16 '22 at 09:38
  • 3
    https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-symbol-objects – deceze Dec 16 '22 at 09:41

1 Answers1

0

I am curious about how Symbols are implemented to achieve uniqueness

Just like objects: when you create a new instance, it has its own identity.

Can anyone shed some light on how for is implemented underneath the hood?

It's basically a Map that caches the created symbols by name. It's called the global symbol registry.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375