What is the motivation for bringing Symbol to ES6?

Technology CommunityCategory: JavaScriptWhat is the motivation for bringing Symbol to ES6?
VietMX Staff asked 3 years ago

Symbols are a new, special kind of object that can be used as a unique property name in objects. Using Symbol instead of string‘s allows different modules to create properties that don’t conflict with one another. Symbols can also be made private, so that their properties can’t be accessed by anyone who doesn’t already have direct access to the Symbol.

Symbols are a new primitive. Just like the numberstring, and boolean primitives, Symbol have a function which can be used to create them. Unlike the other primitives, Symbols do not have a literal syntax (e.g how string have '') – the only way to create them is with the Symbol constructor in the following way:

let symbol = Symbol();

In reality, Symbol‘s are just a slightly different way to attach properties to an object – you could easily provide the well-known Symbols as standard methods, just like Object.prototype.hasOwnProperty which appears in everything that inherits from Object.