Question:
Reading the MDN documentation where it talks about the Symbol
primitive data, no matter 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 Symbol
to debug if console.log()
or debugger
exists.
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:
- Symbol-JavaScript | mdn
- lukehoban/es6features GitHub
- ECMAScript 6 — New Features: Overview & Comparison
Answer:
Symbols are unique data types that are immutable and can be used as object property identifiers. These are like the primitive Number
, String
, and Boolean
types.
To create it, it is done as follows, without using the word new, since the Symbols
have a Symbol
function which is used to create them;
var sym1 = Symbol();
var sym2 = Symbol("foo");
var sym3 = Symbol("foo");
As I commented above, being unique types, it will create a new Symbol which will not be another:
Symbol("foo") === Symbol("foo"); // false
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:
console.log(Symbol('foo')); // prints "Symbol(foo)" to the console.
assert(Symbol('foo').toString() === 'Symbol(foo)');
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.