Symbol data type in JavaScript

Tram Ho

Symbol is a primitive data type of JavaScript, along with string, number, boolean, null and undefined. It was first introduced at ECMAScript 2015 (ES6) a few years ago. It has a very special data type. When you create a Symbol, its value is kept private and for internal use only. You create a Symbol by calling the global Symbol () function:

Every time you call the Symbol () function, they will get a new value and this value is unique, and its value is also different from the value of other Symbols:

You may pass parameters to Symbol () and be used as descriptions for the Symbol itself:

Symbols are often used to define object properties. Usually it is to avoid name conflicts between properties, because no symbols are equal. Or it can also be used to add attributes that cannot be overridden or don’t want to be recognized. For example:

We can also access all of the Symbols assigned to an object by the method *** Object.getOwnPropertySymbols () ***.


Reference: https://flaviocopes.com/javascript-symbols/

Share the news now

Source : Viblo