What are Symbols for in Javascript ES6

Gives a brief explanation of what symbols primitives are for in Javascript ES6 and how they can be used.

Symbols can be used to identify properties on objects. What makes these different to string keys is that they avoid the conflicts that might occur when string keys are used. Take the following example.

class MyClass {
	get prop1() {
  	return this._prop1;
  set prop1(value) {
  	this._prop1 = value;
var c = new MyClass();
c.prop1 = 'foo';
var prop1 = Symbol('prop1');
var prop1Another = Symbol('prop1');
c[prop1] = 'bar'
c[prop1Another] = 'baz'
console.log(c["prop1"]); //foo
console.log(c[prop1]); //bar
console.log(c[prop1Another]); //baz

Every symbol is unique, therefore the symbols prop1 and prop1Another do no conflict, even though they share the same description. Note that the description is entirely optional and is purely meta data; it doesn’t change the behavior of the symbol.

You can read more about the Symbol primitive on Mozilla Developer Network.

Tags: , ,

Leave a Reply