JAVA SCRIP[T - Creating Absolutely Unique Object Property Keys - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript JAVA SCRIP[T - Creating Absolutely Unique Object Property Keys - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Wednesday, March 6, 2019

JAVA SCRIP[T - Creating Absolutely Unique Object Property Keys

 Creating Absolutely Unique Object Property Keys


Problem

You want to create unique object property keys that you’re absolutely confident will remain unique and won’t clash.

Solution

Use the ECMAScript 6 Symbol to create the unique key:


var uniqueId = Symbol();
var newObj = {};
newObj[uniqueId] = 'No two alike';
console.log(newObj[uniqueId]); // 'No two alike'
var uniqueId2 = Symbol('one');
var uniqueId3 = Symbol('one');


EXPLAIN

Symbol is one of those new additions with ECMAScript 6 that you didn’t know you needed until you saw it. We’ve become rather adept over the years at dealing with not having the capability to create unique identifiers. 

But being adept at working around a gap in a language isn’t the same as having the language flexibly move to fill in the gap. In the solution, a new identifier, uniqueId, is created to act as property identifier. 

Even if some other library wanted to use the exact same identifier, the two uses can’t clash because the new identifier would just be returned when making the call to Symbol, even with the same optional string, as demonstrated with the second and third unique identifiers. Symbol can also be used to create a set of enumerated values: 


var green = Symbol();
var red = Symbol();
function switchLight(light) {
 if (light === green) {
 console.log("Turning light red");
 light = red;
 } else {
 console.log("Turning light green");
 light = green;
 }
 return light;
}
var light = green;
light = switchLight(light);
light = switchLight(light);

Instead of creating a number or string variables and then assigning values (and having to perform type checking as well as value checking when the value is evaluated), you can just create a new enumerated identifier.

Symbol is not like String or Number, in that you don’t create a new instance of an object using new. You call it as a Function, and the new identifier is returned.

No comments:

Post a Comment

Post Top Ad