19
In the new Javascript specification Ecmascript (ES6) a new primitive type was created called Symbol()
what use it is?
19
In the new Javascript specification Ecmascript (ES6) a new primitive type was created called Symbol()
what use it is?
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:
Browser other questions tagged javascript ecmascript-6
You are not signed in. Login or sign up in order to post.
+1, cool, but in which scenarios it will be useful?
– Gabriel Rodrigues
@Gabrielrodrigues I gathered ideas, if more come along.
– Sergio
I think the main idea is that they are used as property names (Keys). Native object keys are only strings for ES5 compatibility-
– bfavaretto
Bruh, that’s a +1 answer
– StillBuggin
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
Symbol
s are still enumerable, right? Using this your last code as an example, it wouldn’t be the case to dovar mensagemSecreta = obj[Object.getOwnPropertySymbols(obj)[0]];
and thus have access to value even without knowing the key?– mgibsonbr
@mgibsonbr you’re right. And using
Symbol.for('str');
it’s still easier withSymbol.keyFor(instancia)
(jsfiddle). Good to see you! If you were around more often the answers would be even more in order :)– Sergio