Reading the MDN documentation where the primitive data is talked about, no matter Symbol
how much I read and reread, I don't understand what would be a use case for said element other than to iterate Symbol.iterator
.
The documentation says that its use is for debugging purposes , but even with that I don't understand why use a to debug if or Symbol
exists .console.log()
debugger
I understand that it is a primitive data and therefore immutable. In the examples I have seen that they do something like the following:
var sym = Symbol('Llave'),
obj = {
[sym]: 'valor'
};
console.log(obj[sym]); // valor
console.log(obj['Llave']); // undefined
Why use a Symbol
? if a traditional key (key: value) can be used.
Sources:
Symbols are unique data types that are immutable and can be used as object property identifiers. These are like the types
Number
,String
, andBoolean
primitives.To create it, it is done as follows, without using the word new, since they
Symbols
have a functionSymbol
which is used to create them;As I commented above, being unique types, it will create a new Symbol which will not be another:
About
debuging
These are considered powerful, since they have a description, which is used only for debugging to make life easier when debugging by console:What are they good for?:
To create and store values like
integer
andstring
that will not change.It can be used to store custom metadata for objects, which are children of the current object.
Conclusion:
They are small constants that have some extra properties that allow us to work better in debug and save unique values.
A good resource is this page where there is an example, and they explain much more extensively what symbols are.
Since @WilfredoP hasn't mentioned global symbols I'm going to take advantage of:
Here,
s1
ands2
are basically the same symbol. But how a symbol is coded is not as important as its purpose:They
Symbols
are part of a movement Javascript is making toward metaprogramming . And they are not alone in this, ECMAScript 2015 includes 2 other additions that point in that line which are Proxy and Reflect .Therefore, its use is very varied. The question is what semantics these will have for your application.
There are some well known symbols!
Symbol.hasInstance: instanceof
Symbol.hasInstance
is the symbol that controls the behavior ofinstanceof
. That is,A instanceof B
it is equivalentB[Symbol.hasInstance](A)
.Example:
Symbol.iterator
Overloading the method
objeto[Symbol.iterator]
allows you to change the behavior of the operatorof
in a blockfor .. of
if it is overloaded as a generator function.Example:
There is quite a long list of these symbols pre-defined by the standard. But not all of them are 100% implemented in all browsers.