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.
– LeAndrade