ES6 Symbols

node v0.12.18
version: 2.0.0
Symbols are a new data type in JavaScript that you can use to add properties to objects without colliding with other strings:
var myToStringSymbol = Symbol("toString")
var object = { }; // We'll use this symbol to describe the method without overwriting it. object[myToStringSymbol] = "this method will print a string"; // Print both, to show they're both still there. console.log(object[myToStringSymbol], object["toString"]);
You can use many of the built in symbols to take advantage of the new features added to objects in ES6. For example, we can use the global iterator Symbol to define how a custom object should behave in for...of:
var cart = { items: ["pizza", "car", "pastrami"], [Symbol.iterator] : function* () { for (var i = 0; i < this.items.length; ++i) yield this.items[i]; } } for (item of cart) console.log(item + " is in your cart!");
To learn more about Symbols, go to

1 comment

  • posted 3 years ago by hexorarix

sign in to comment