Now features in ES6. 1)Variable declaration with let and const 2)Block and IIFEs 3)Strings 4)Arrow functions 5)Destructing 6)Arrays 7)The spread operator 8)Rest and default parameter 9)Maps 10)Classes and subclasses

We are on git also : 

After coming of ES6 / ES2015 , the javascript programming became very secure and fantastic. We can look below the list of new features introduced in Es6.

1)Variable declaration with let and const

2)Block and IIFEs

3)Strings

4)Arrow functions

5)Destructing

6)Arrays

7)The spread operator

8)Rest and default parameter

9)Maps

10)Classes and subclasses

Variable declaration with let and const

In Es5 we are using var keyword to create the variable. But, in Es6 we are using let and const keywords for creating the variables.

Note : In Es5 the var is function scoped. Whereas in Es6 the let and const variables are block scoped.

//ES5

We use var

//Es6

We can use const and let. So, let will be the alternative for the var. Also, it is mutable like var keyword. It means that variables created with the help of var keyword(Es5) or with let keyword(Es6) are mutable. We can change the value stored inside them. But if we want to go with non mutable items , we have to use const keyword.

Note : But, const is not mutable

Note : In Es6 we use const for non mutable items. And, we use let for mutable items

Difference between the function scoped and block scoped :

<script>

 

 

</script>

The log in ES6 will give error . Because  the let is block scoped, whereas the var is function scoped.It works with if block , for block , while block.

Also , the var is accessible inside the function not outside the function . It is function scoped. SO if we put the var code outside the function , it is not accessible.

Assignment : Please explain the function scoped and the block scoped in detail with example. Give example of Es5 and Es6.

q)Give an example of accessing the let and const inside the block scope :

Sol :

<script>

 

//Status : Above example will run fine

Give an example of accessing the let and const outside the block scope :

//Condition 2, where we are accessing the let and const outside the if block

//Status : Give error

Give an example of accessing the let and const outside the block scope with global declaration of variables :

//Condition 3, where we are accessing the let and const outside the if block. But this time we will declare it outside the block scope

</script>

Now, Let us see the hoisting in ES5 and ES6

q)Give an example of hoisting in Es5 and also in Es6 :

/

Note : Here in execution context , all the variables are hoisted and set to undefined

 

Note : All in Es6 this is good thing as it prevent further errors.

q)Give an example of let operator of Es6 in for loop block

Block and IIFEs

In ES5 , we are using self calling function IIFE (Immediately invoked function ) to maintain the private variables. Because as the variables created with var keyword is function scope , so after function they can not be accessed.

We use for the data privacy.

IIFE : Immediately  invoked function. In ES5 we were using IIFE for data privacy.

//Es5 using IIFE

(function(){

var a = 2;

var b = 5;

})();

console.log(a+b);

var are function scoped. So, can not be accessed outside the self calling function

But in Es6 we have more better approach for the data privacy and we can use block instead

Now block not only means if condition , for loop . But we can create the block simply by using two curly braces. This curly braces will make private scope for let and const

{

}

Example :

//Es6

<script>

{

  let a = 2;

  const b = 5;

}

console.log(a+b);

</script>

Output : Uncaught ReferenceError: a is not defined at a6.html:9

a and b can’t be accessed outside the block.

Note : They are block scoped and not the function scoped

Again take a example :

{

var a = 10;

}

console.log(a);

Output : 10; // Because the var is function scoped

Strings

In ES5 we are using the + operator to concatenate the string with variable. But, in ES6 we have the string literal to handle string data. For this we are using back tik.

Let us take an example to see how string is handled in ES5 using + operator. Also, we use back tick in ES6 to handle string

q)Take firstName , lastName , yearOfBirth . Also take a function with name calcAge(year).

 

Display all records with Es5. ALso with Es6

 

Solution :

<script>

//ES5

var firstName = “Mohan”;

var lastName = “Kumar”;

var yearOfBirth = 1990;

function calculateAge(year){

  return (2018year);

}

console.log(‘The person with name ‘+firstName+‘ ‘+lastName+‘ born in ‘+yearOfBirth+‘ is of age ‘+calculateAge(yearOfBirth)+‘ Years.’)

 

//Es6

var firstName = “Mohan”;

var lastName = “Kumar”;

var yearOfBirth = 1990;

function calculateAge(year){

  return (2018year);

}

console.log(The person with name ${firstName} ${lastName} born in ${yearOfBirth} is of age   ${calculateAge(yearOfBirth)} Years.);

</script>

 

Arrow operators in ES6

Example 1 : Write a code to take an array of birthdates in year. Then map it find the array of ages. Use both ES5 and ES6

<script>

//Es5 using IIFE

var dobs = [1990,1989,1988,1967];

var ages = dobs.map(function(ele){

  return (2018ele);

});

console.log(ages);

//Es6 using IIFE

const dobs_new = [1990,1989,1988,1967];

const ages_new = dobs_new.map(ele=>2018ele);

console.log(ages_new);

</script>

Example 2 : Write a code to take an array of birth dates in year. Then map it and find array of string ages.

<script>

//Es6 using IIFE

const dobs_new = [1990,1989,1988,1967];

let ages_new = dobs_new.map((ele,index)=>{

  let current = new Date().getFullYear()-ele;

  return Person ${index} : ${current-ele} years;

});

console.log(ages_new);

</script>

Default Parameter in ES6

In Es5 , we do not have the concept of default parameters. But we are handling it somehow inside our code

By Pankaj Kumar Agarwal

//In Es6 , we use default parameters

var Person = function(firstName,lastName,yearOfBirth=1990,nationality=’Indian’){ this.firstName = firstName;

this.lastName = lastName;

this.yearOfBirth = yearOfBirth;

this.nationality = nationality; }

Note : So , if we are calling the about function with first 2 parameters of firstName and lastName , then yearOfBirth will take default value of 1990. Also, if we are not passing any value to nationality , then it will take Indian as default value

Destructing In ECMA6 :

Destructing is used to store the different elements of array and object.

It gives us an very convenient way to extract data from the array or any object.

Now, let us take we have an array filled with some data. And , we want to store each of the elements of the array in single variable.  In Es5 we have to take separate variables. But in ES6 we can make use of destructing.

Spread Operator in ECMA6 :

It is a new operator in javascript, That is spread operator.

It is very easy way to expand elements of array. It is used in arguments  in function call. So, what we mean by expand elements.

<script>

function familyIncome(mohanIncome,sohanIncome,rohanIncome){

  return (mohanIncome+sohanIncome+rohanIncome);

}

var totalfamilyIncome = familyIncome(200000,150000,100000);

console.log(‘The total income is ‘+totalfamilyIncome);

//Now, suppose that all the above incomes are in array. So how we will pass the array value inside the function

var incomes = [200000,150000,100000];

//Now we will use bind , call , apply methods to achive this

//start withh apply method because it uses an array.

var totalNewFamilyIncome = familyIncome.apply(null,incomes);

//I do not want to use  this operator. So, i will pass null here. The incomes array get spread to the 3 parameters of the familyIncome() function.

console.log(‘The new total income is ‘+totalNewFamilyIncome);

//ES6.

//In ES6 we have more better approach to achive this. That is spread operator. The spread operator starts with 3 dots. (…x)

const newFamilyIncome3 = familyIncome(…incomes);

console.log(‘The new final income is ‘+newFamilyIncome3);

</script>

 

Let us check for other use case for the spread operator :

The spread operator is also used to merge the two arrays.

//Let us merge two arrays with help of spread operator

let category1Products = [‘Cricket’,‘Football’,‘Tennis’,‘BasketBall’];

let category2Products = [‘Cap’,‘T-Shirt’,‘Loose Pant’];

const newCategoryProducts = […category1Products,…category2Products];

console.log(‘The list of new product list is ‘,newCategoryProducts);

//Output : The list of new product list is  (7) [“Cricket”, “Football”, “Tennis”, “BasketBall”, “Cap”, “T-Shirt”, “Loose Pant”]

Final Touch :

Now, let us take an example of real dom elements. Let us , suppose we have one heading text. Also, we have 3 divs with background-color as red , green , blue. Get the reference of all 4 (h1+3 divs). Change color of all the divs text

<html>

<head>

<style>

.box{

  width : 100px;

  height : 100px;

}

.red{

  background-color : red;

}

.blue{

  background-color : blue;

}

.green{

  background-color : green;

}

</style>

</head

<body>

<h1>The list of cars</h1>

<div class=“box red”>Santro</div>

<div class=“box blue”>Ciana</div>

<div class=“box green”>Corolla</div>

</body>

<script>

var h = document.querySelector(‘h1’);

var list2 = document.querySelectorAll(‘.box’);

var list3 = [h,…list2];

Array.from(list3).forEach(function(t){

  t.style.color = ‘red’;

})

console.log(‘The new far good list is ‘+list3);

//The above code will change the color for all elements  including h1 and all divs

</script>

</html>

Rest operator in ECMA6 :

Both the rest and spread look same but they are totally different from each other.

The spread operator actually takes an array and then really transform it into single values.  While the rest parameters receive a set of single value and convert it into the array whenever we call  a function with multiple parameters.

 

<script>

//In ES5 whenever the list of parameters are not fixed. We generally use arguments keyword

//Arguments keyword is very similar to the this variable. This is a variable which each execution context is access to.

function totalMarks(){

  console.log(arguments);

}

//We have the access to arguments in all the function

totalMarks(99,92,88);

//Output : Arguments(3) [1, 2, 25, callee: ƒ, Symbol(Symbol.iterator): ƒ]

//__proto__ : It tells that what we console is an object. Not an array

//It is not an array. but we want to use it as an array. So that we can iterate through it.

 

function totalMarks(){

  console.log(arguments);

  var argArray = Array.prototype.slice.call(arguments);

  console.log(argArray);

  //Now, we call call forEach on this array

  argArray.forEach(function(mark){

      console.log(mark)

  })

}

totalMarks(11,122,43,567);

//So, the above function will work will all number of arguments

totalMarks(11,122,43,567,43,88);//This also works
//Now, let us solve this above problem with ES6

function totalMarks(…marks){

//whatever the parameters we will pass to the totalMarks() , it will transform it into an array and store the items into marks variable.

console.log(“the new mark list in ES6”,marks);

marks.forEach(function(mark){

      console.log(mark)

  })

}

//here in ES6 , we do not need to convert the parameter to array.Simply the rest parameter is array

totalMarks(11,122,43,567);

//In ES5 parameters is of object type. But, in Es6 rest parameter is of array type

//Apply limit in rest parameter

function totalMarks(passingMark,…marks){

//whatever the parameters we will pass to the totalMarks() , it will transform it into an array and store the items into marks variable.

console.log(“the new mark list length with limit in ES6”,marks.length);

marks.forEach(function(mark){

      console.log(‘Pass status is ‘+(mark>=passingMark));

  })

}

totalMarks(90,99,87,98,88)

/*Output : Pass status is true

a12.html:48 Pass status is false

a12.html:48 Pass status is true

a12.html:48 Pass status is false*/

</script>

By Pankaj Kumar Agarwal

 

Leave a reply:

Your email address will not be published.