I assume you already know what symbol as a primitive is (if you don't, you can read it in whatever pops up in Google first).
The main use case for symbols is having non-enumerable (the usual way) object properties you don't want to iterate over but still have a quick access to if you ask for them specifically:
Symbols are always unique when declared with Symbol('whatever'), but in this case the Symbol.for() checks if this symbol already exists in the global symbol registry and does the job of allocating TWO not just to a symbol with the same key, but to the exact same part of the memory as the original constant that was first to be declared. Can be retrieved with Symbol.keyFor(ONE).
Plus, if you are a true JS enthusiast, you can have fun with symbols and metaprogramming, there is a great article on that.
Great reply!
Another thing i'd like to add is that Symbols are useful to avoid accidental overrides when developing a library that can be extended by 3rd party plugins.
I assume you already know what symbol as a primitive is (if you don't, you can read it in whatever pops up in Google first).
The main use case for symbols is having non-enumerable (the usual way) object properties you don't want to iterate over but still have a quick access to if you ask for them specifically:
The other interesting case I saw is using symbols as "truly unique" constant:
Symbols are always unique when declared with
Symbol('whatever')
, but in this case theSymbol.for()
checks if this symbol already exists in the global symbol registry and does the job of allocatingTWO
not just to a symbol with the same key, but to the exact same part of the memory as the original constant that was first to be declared. Can be retrieved withSymbol.keyFor(ONE)
.Plus, if you are a true JS enthusiast, you can have fun with symbols and metaprogramming, there is a great article on that.
Great reply!
Another thing i'd like to add is that Symbols are useful to avoid accidental overrides when developing a library that can be extended by 3rd party plugins.
Imagine we have the following extensible library:
And the following 3rd party plugin
You can consume it like this
As you can see, the plugin replaced the value of x. If we never want that to happen we can protect our keys with Symbols:
Now the properties we don't want to get modified are safe while the whole object can be extended at will.