How does Symbol work on ES6?

Asked

Viewed 403 times

19

In the new Javascript specification Ecmascript (ES6) a new primitive type was created called Symbol() what use it is?

1 answer

16


Symbol() is a new primitive. How Function, Object and Number.

What is special is that it generates something unique. A Symbol is always unique. Some say it generates tokens (for being unique), always different.

That is to say:

var a = Symbol(123);
var b = Symbol(123);
console.log(a == b, a === b); // false, false

es6fiddle: http://www.es6fiddle.net/ihpaffj0/

This is curiously true even in object property names.

var obj = {};
var a = obj[Symbol('prop')] = 'foo';
var b = obj[Symbol('prop')] = 'bar';
console.log(a, b, obj[Symbol('prop')]); // 'foo', 'bar', <vazio>

es6fiddle: http://www.es6fiddle.net/ihpapvuv/

Where it might be useful?

It’s hard to guess every use case, but some I imagine:

  • generate Symbols unicos for ids and/or sessions
  • avoid object property name bumps

Good reading in English

  • 1

    +1, cool, but in which scenarios it will be useful?

  • @Gabrielrodrigues I gathered ideas, if more come along.

  • I think the main idea is that they are used as property names (Keys). Native object keys are only strings for ES5 compatibility-

  • 1

    Bruh, that’s a +1 answer

  • This question of only being able to access a property if you have the corresponding key seems strange to me. After all, the properties whose keys are Symbols are still enumerable, right? Using this your last code as an example, it wouldn’t be the case to do var mensagemSecreta = obj[Object.getOwnPropertySymbols(obj)[0]]; and thus have access to value even without knowing the key?

  • 1

    @mgibsonbr you’re right. And using Symbol.for('str'); it’s still easier with Symbol.keyFor(instancia) (jsfiddle). Good to see you! If you were around more often the answers would be even more in order :)

Show 1 more comment

Browser other questions tagged

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