What is a Symbol for in JavaScript? (ES6)

11

Reading the MDN documentation where we talk about the primitive data Symbol for more that I read and reread I do not understand what would be a use case for that element more than to iterate Symbol.iterator .

The documentation says that its use is for debug purposes, but even with this I do not understand why to use Symbol to debug if there is console.log() or 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 you can use a traditional key (key: value).

Sources:

asked by Chofoteddy 29.12.2015 в 18:58
source

2 answers

7

Symbols are a unique data type that is immutable and can be used as an object property identifier. These are like the types Number , String , and Boolean primitives.

To create it is done in the following way, without using the word new, since the Symbols have a function Symbol which is used to create them;

var sym1 = Symbol();
var sym2 = Symbol("foo");
var sym3 = Symbol("foo");

As mentioned above, being unique types, he 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 to debug 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 such as integer and string that will not change.

  • Can be used to save custom metadata of the objects, which are secondary to the current object.

  • Conclusion:

    They are small constants that have some extra properties, which 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 extensive what which are the symbols.

        
    answered by 29.12.2015 / 19:15
    source
    5

    Since @WilfredoP has not mentioned the global symbols I will take advantage of:

    var s1 = Symbol.for('foo');
    var s2 = Symbol.for('foo');
    s1 === s2 // retorna true, ya que Symbol.for(<name>) genera símbolos globales.
    

    Here, s1 and s2 are basically the same symbol. But how a symbol elbows is not as important as its purpose:

    The Symbols are part of a movement that is doing Javascript towards the metaprogramacion . And they are not alone in this, ECMAScript 2015 includes other 2 additions that point in that line that are Proxy and Reflect .

    Therefore, its use is very varied. The question is why semantics will have these for your application.

    There are some well-known symbols!

    Symbol.hasInstance: instanceof

    Symbol.hasInstance is the symbol that controls the behavior of instanceof . That is, A instanceof B is equivalent B[Symbol.hasInstance](A) .

    Example:

    class MiArray {  
        // aquí sobrecargo el operador instanceof 
        static [Symbol.hasInstance](otro) {
            return Array.isArray(otro);
        }
    }
    assert([] instanceof MiArray); // pasa, por evaluarse como true
    

    Symbol.iterator

    Supercharging the objeto[Symbol.iterator] method allows changing the behavior of the of operator in a for .. of block if it is overloaded as a generating function.

    Example:

    class IterarSaltando {  
      *[Symbol.iterator]() {
        var i = 0;
        while(this[i] !== undefined) {
          yield this[i];
          i+=2;
        }
      }
    }
    var iterarSaltando = new IterarSaltando();
    iterarSaltando[0] = '1';
    iterarSaltando[1] = '2';
    iterarSaltando[2] = '3';
    for(var value of iterarSaltando) {  
        console.log(value); // 1, luego 3
    }
    

    There is a fairly long list of these pre-symbols defined by the standard. But not all are 100% implemented in all browsers.

        
    answered by 29.12.2015 в 20:00