How does Symbol work in ES6?

18

In the new Javascript specification ECMAScript (ES6) was created a new primitive type called Symbol() what is its usefulness? / p>     

asked by anonymous 02.12.2015 / 20:41

1 answer

15

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

What is special is that it generates something unique. A Symbol is always unique. Some people say that it generates tokens (because they are unique), always different.

That is:

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

es6fiddle: link

This is true even interestingly 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: link

Where can it be useful?

It's hard to guess all use cases, but some I imagine:

  • Generate unique Symbols for ids and / or sessions
  • avoiding object property name clashes

Good reading in English

02.12.2015 / 22:00