What is a Symbol used for in JavaScript? (ES6)


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.



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?:

  1. To create and store values ​​like integer and string that will not change.

  2. It can be used to store custom metadata for objects, which are children of the current object.


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.

Scroll to Top