Symbol In ES6

This post is about new data type in ES6 that is Symbol

String ,number , null , undefined ,  boolean ,  in ES5

But in ES6 , we have symbol as new data type. The purpose of symbol is to create unique id. The funny thing is that we never get the access to that unique id. 

What is symbol ?

It is a new primitive type in JS. 

Just like other primitive types like : 

Number()

String()

Boolean()

 

Symbol() : new member introduced in ES6

It is a special value that is unique. We use it whenever we need  a unique value. We use it to avoid the attribute name conflict in an object. 

We do not need to call String(). Simply we write anything in “”.

We do not need to write Number(4) . Simply we write 4

Note : There is no shortcut syntax for Symbol().

Symbol() or Symbol(‘Maria’) // Maria is for label. It is for debugging. Each time we call Symbol().They get a new value. 

Example 1 : (Proof)

Let sym1 = Symbol()

Let sym2 = Symbol();

//check both variables in browser

console.log(sym1===sym2); //false

 

Example 2 : (Now check after passing descriptor)

Let sym1=Symbol(‘Apple’);

Let sym2=Symbol(‘Apple’);

//Check on browser. They help in debugging only !

console.log(sym1 == sym2);//false

 

Example 3 :

Why we need Symbol ? Why we need unique values from Symbol()

Ans : Every symbol value returned from Symbol() is unique.  A symbol value may be used as an identifier for object properties; this is the data type’s only purpose.  

Ref : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol

Suppose we are getting the object from some unknown source.So adding the property may override it.So we are adding unique identifier as unique. To guarantee that it is not conflicting.

let obj = {

  id : 1,

  name : "A",

  age : 21

}

obj.id = 22;

Above we are assigning id two times :

So, older value gets overridden. The solution is :

let person = {

  id : 1,

  name : "Mohan",

  sal : 200

}

let newId = Symbol('id');

person[newId] = 2;

console.log('The id is ',person);

The inline example :

let newId = Symbol('id');

let person = {

  id : 1,

  name : "Mohan",

  sal : 500,

  [newId] : 600

}

console.log(person)

 

Example 4 :

They act as a private property. They are not shown by using the getOwnPropertyNames()

console.log(‘List all properties ‘,Object.getOwnPropertyNames(person))

Also , with for in we can not find it

> for(x in obj){}

Output : List all properties  (3) [“id”, “name”, “sal”]

Note : We can find them . They are not secret

console.log(‘The symbols are ‘,Object.getOwnPropertySymbols(person));

 

Example 5 :

Symbol.for()

It will give you a symbol based on descriptor. But it will not be unique. 

All are added to global symbol space. 

let cam1 = Symbol(‘Nikon’);

let cam2 = Symbol(‘Nikon’);

Note : Both the Symbols gets added to global symbol space.

console.log(cam1==cam2) // true

 

Example 6A :

const RED= Symbol(‘red’);

const ORANGE= Symbol(‘orange’);

const YELLOW= Symbol(‘yellow’);

const BLUE= Symbol(‘blue’);

const cat = ‘blue’;//get same result for blue also

function getThreatLevel(color){

  switch(color){

    case RED:

      return ‘severe’;

    case ORANGE:

      return “High”;

    case YELLOW:

      return ‘eleveted’;

    case BLUE:

      return ‘low’;

    default:

      console.log(‘Do not know the color’)

  }

}

 

Example6B : Let us see the use cases

How to store metadata in object.

class Train{

    constructor(){

    this.length = 0;

  }

  add(car,des){

    this[car] = des;

    this.length++;

  }

}

let obj = new Train();

obj.add(‘refrigerator car’,’Cattle’);

obj.add(‘flat car’,’aircraft’);

obj.add(‘Container car’,’Milk’);

for(let key in obj){

  console.log(key,”==> “,obj[key]);

}

 

Note : Length is also coming in key

To solve this :

let length = Symbol(‘length’);

class Train{

  

  constructor(){

    this[length] = 0;

  }

  

 

  add(car,des){

    this[car] = des;

    this[length]++;

  }

}

 

let obj = new Train();

obj.add(‘refrigerator car’,’Cattle’);

obj.add(‘flat car’,’aircraft’);

obj.add(‘Container car’,’Milk’);

 

for(let key in obj){

  console.log(key,”==> “,obj[key]);

}

 

 

 

let s = Symbol();

console.log(typeof s);// Symbol

 

Example 7 :

 

——————————————————————————–

 

let s = Symbol(‘First Symbol’);

console.log(‘The type of s ‘,typeof s);

console.log(‘The symbol details ‘,s.toString());

 

let s2 = Symbol();

let s3 = Symbol();

console.log(‘The status is ‘, (s2==s3))

 

let s22 = Symbol(“Great”);

let s33 = Symbol(“Great”);

console.log(‘The cam status is ‘, (s22==s33))

//symbol create a different id’s. So both s2 and s3 have different id’s

//A symbol is always going to create unique id

//We have the symbol registry. So, to add the symbol to the registery

//

let x1 = Symbol.for(“Apple”);

console.log(‘The apple detail is ‘,x1);

let x2 = Symbol.for(‘Apple’);

console.log(‘The 2nd apple is ‘,x2);

console.log(x1===x2);//true : Bacause , A new Symbol is created in global registry with this description

 

 

 console.log(‘The key is s’,Symbol.keyFor(x1));

The for -of loop : The for-of loop does not works with the objects by default. 

let obj = {

  name : “Mohan”,

  age : 21,

  sal : 1200

}

 

for(let x of obj){

  console.log(“==> “+x);

}

 

Note : ABove error

How to make object iterable ?

Ans : 

 

https://www.youtube.com/watch?v=TJpkYvSREtM

 

Site Footer