How does the Symbol() data type work?

Asked

Viewed 58 times

1

The type of data Symbol() has been implemented in the language since version 6 or 2015, but I did not understand its actual use. Looking at some practical examples found on the web, I saw examples to assign new attributes to objects:

let usuario = {
  nome: "Fulano"
};

let id = Symbol("id");

usuario[id] = 1;

console.log(usuario[id]);

But if you log the object I see that it has no such attribute:

let usuario = {
  nome: "Fulano"
};

let id = Symbol("id");

usuario[id] = 1;

console.log(usuario[id]);
console.log(usuario)

If I can access the id through the object usuario, pq in the log the object does not have the id attribute?

1 answer

1


The detail of the log is that it does not have a well defined behavior by Ecmascript, so we see some differences in its behavior in different browsers, such as when you log a HTMLElement in Chrome it prints the HTML, while Firefox prints the object.

Symbols are object properties, and they may or may not appear in your log depending on the implementation. But unlike other properties, by default Symbols are not enumerable, which may be the reason you can’t see it in your log:

var obj = {
    a: 'prop a'
}

Object.defineProperty(obj, 'b',{
    value: 'prop b',
    enumerable: false
})

console.log(obj.a)
console.log(obj.b)
console.log(obj)

Notice that in Stackoverflow the property b does not appear in the log, although it exists. The difference between a enumerable property and a nonenumerable property is that nonenumerable properties are not returned by the method Object.keys() and are not even iterated in ties for...in

As for the usefulness of Symbols... I’ve heard that Symbols can be used to create inaccessible properties, that is, private, but this is no longer a good practice since new Javascript implementations already have a native way of declaring private properties.

The use of Symbols usually falls into interaction with Javascript operators, such as the Symbol.iterator for example that is accessed by the operator of within a loop for...of:

var listaEncadeada = {
  inicio: { val: 1, prox: { val: 2, prox: { val: 3, prox: null } } },
  
  [Symbol.iterator]: function*() {
    var nodo = this.inicio
    while (nodo) {
      yield nodo.val
      nodo = nodo.prox
    }
  }
}

for (var val of listaEncadeada) {
  console.log(val)
}

  • Valeu man, nice answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.