Hi, is there any use case for the symbol in JavaScript?
I'm looking for real-world examples.
Hi, is there any use case for the symbol in JavaScript?
I'm looking for real-world examples.
For further actions, you may consider blocking this person and/or reporting abuse
Alex Abiola -
Ricardo Sueiras -
AdriánColom -
Sospeter Mong'are -
Top comments (9)
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.
I'm interested in this question too. I've been reading a lot about symbols and suggested use cases, but can't find an example of some real world usage.
If you want an overview of symbols in js, I think ES6 in Depth: Symbols is excellent.
One common use case is to define
[Symbol.iterator]
or[Symbol.asyncIterator]
to create custom iterables. e.g:The Iterators Are Coming! Iterator and asyncIterator in JavaScript
Nested Software
What symbol is that?
Is there a "the symbol" meaning in javascript that I'm not aware of?
I guess: developer.mozilla.org/en-US/docs/W...
developer.mozilla.org/en-US/docs/W...
Is something not being rendered correctly? Can you post an image of the symbol you're interested in?
developer.mozilla.org/en-US/docs/W...