JavaScript Symbol ES6
A symbol is a unique and immutable data type and may be used as an identifier for object properties. Symbol can have an optional description, but for debugging purposes only.
Syntax:
var s1 = Symbol([description]);
[description]: It is optional parameter and it is only used for the debugging purposes only.
When we use every time Symbol() every time it give the unique and immutable identifier that may be string or number of mixture of both, but we can not convert the identifier into string.
It is useful when you have to create the dynamically properties of the object.
Example:
var s1 = Symbol(); alert(String(s1)); // Symbol() var s2 = Symbol("JavaScript Hive"); alert(String(s2)); // Symbol(JavaScript Hive)
If you create the two symbol at time than it provides to you the two unique identifier, even if you pass the same parameter to the Symbol() it also provides to you two unique identifier.
Example:
var s1 = Symbol("ONE"); var s2 = Symbol("ONE"); alert(String(s1)); // Symbol(ONE) alert(String(s2)); // Symbol(ONE) alert(s1==s2); // false alert(typeof s1 === typeof s2); // true
If you check the above example than you found that we create the two object of the Symbol with the Symbol(“ONE”), If we check the s1==s2 than it returns the false, because the it give the unique identifier every time and it does not consider the parameter white generating the identifier.
NOTE: You can not have to use the new keyword with the Symbol(). It does not allow you to use, when you use it it will throws the error.
var sym = new Symbol(); // it will show the error and your program exceution is ended here.
JavaScript Symbol as property key:
Symbol also can be used as property key of the object.
var obj = {}; var FIRST_NAME = Symbol("FirstName"); var LAST_NAME = Symbol("LastName"); obj[FIRST_NAME] = "Mr. James "; obj[LAST_NAME] = "Bond"; alert("Welcome " + obj[FIRST_NAME] + " " + obj[LAST_NAME]); // Welcome Mr. James Bond
Example 2:
var FIRST_NAME = Symbol("FirstName"); var LAST_NAME = Symbol("LastName"); var obj = { [FIRST_NAME] : "Mr. James", [LAST_NAME] : "Bond", }; alert("Welcome, " + obj[FIRST_NAME] + " " + obj[LAST_NAME]); // Welcome Mr. James Bond
Please post your reviews below…
Happy Coding...
🙂