Categories
ECMAScript Javascript

Symbols

/**
 * Symbol is primitive data type that helps in meta programming
 * Symbol is memory location to store data, but symbol is immutable and unique
 * Hence data is better encapsulated in the form of symbol 
 */

//to demonstrate uniqueness of Symbol
const s1 = Symbol("Hi");
const s2 = Symbol("Hi");
const string1 = "Hi";
const string2 = "Hi";
console.log("string1==string2",(string1==string2));
console.log("s1==s2",(s1==s2));

//Symbol.for - if symbol already present in registry, use same else create new one.
const userName = Symbol.for('userName') // creates a new Symbol in registry
   const user_Name = Symbol.for('userName') // reuses already created Symbol
   console.log(userName == user_Name)    
   const studentName = Symbol("studentName") // creates symbol but not in registry
   const student_Name = Symbol.for("studentName")// creates a new Symbol in registry
   console.log(studentName == student_Name)
   
//Symbol.keyFor - to return symbol from registry
const user_Name2 = Symbol.for('userName');
console.log("user_Name from registry ::" + Symbol.keyFor(user_Name2));

const userName2 = Symbol('userName');
console.log("userName from registry ::" + Symbol.keyFor(userName2));


const COLOR = Symbol()
const MODEL = Symbol()
const MFG = Symbol()
class CAR {
   constructor(color ,make,model){
   this[COLOR] = color;
   this[MFG] = make;
   this[MODEL] = model;
}
}

var civic = new CAR("Red","Honda","2020");
console.log("car info civic ", civic[COLOR],civic[MODEL],civic[MFG]);

Output

Leave a comment

Design a site like this with WordPress.com
Get started