Learn ES6 in 20 Minutes

Javascript is the most popular scripting language nowadays which works on ECMAScript specifications. After the success of the ES5. Javascript 6 edition or ES6 is the most demanding among programmers. So in this article, we will cover an overview of es6 and cover most of its features.

let and var

If we are talking about let and var that means the variable is mutable.


// For let
let i;
i = 0;
Or 
let i = 0; 

// why mutable
i = 10; // we can change

// for var
var i;
or
var i = 0;

// why mutable
i = 10; // we can change

Difference between var and let

  1. The main difference between let and var is that let always works with block scope and var works with function scope.

    
    for (var i = 0; i < 2; i++) { 
    	console.log("Case: " + i); 
    } 
    console.log("Final Value of I : " + i);
    
    // Output:
    // Case: 0
    // Case: 1
    // Final Value of I: 2
    
    

    here you can see after completing for loop the final value of i is remain usable outside for loop.

    
    // let case  
    for (let i = 0; i < 2; i++) { 
        console.log("Case: " + i); 
    } 
    console.log("Final Value of I : " + i);
    
    // Output:
    // Case: 0
    // Case: 1
    // ReferenceError: i is not defined
    
    

    Here you can see after completing for loop i is no more usable so we will get ReferenceError.

  2. 
    let can't redeclare but we can redeclare var
    var i = 12;
    var i = 13;
    
    // for let
    let i = 12;
    let i = 13; // Uncaught SyntaxError: redeclaration of let i
    
    

const

If we are talking about const that means the variable will be immutable and must initialise with or assign some value.


const PI = 3.14; // must initialize
PI = 3.142 // invalid assignment to const 'PI' 

So const variable can’t reinitialize.

Spacial const case


const arr = ['one', 'two'];
for (const elem of arr) {
  console.log(elem);
}
// Output:
// 'one'
// 'two'

const element creates a new binding for all iterations that way it works fine.

Destructuring

To understand destructuring, we need to understand this scenario. Suppose that we have a directions array and we want to use all directions separately.


let directions = ["east", "west", "north", "south"];
var east = directions[0],
west = directions[1],
north = directions[2],
south= directions[3];

but es6 provides us with an elegant way to achieve this in a proper manner.


var [east, west, north, south] = directions;
console.log(east, west); // east west

the same scenario can use for the javascript object.


let directions = {
  e: "east",
  w: "west",
  n: "north",
  s: "south"
};

const { e: east, w: west, n: north, s: south } = directions;
console.log(east, west); // east-west

the left side will be for the object key and the right side will be variable.

Map, WeakMap

ES6 introduced these new data types in ES6. A map is just like a JavaScript Object (key-value pair) but more powerful as compared to a JavaScript regular object; in the Map, all values can be used as a key (object key must be a string or symbol) as always remember insertion order of keys.


const dMap = new Map();
dMap.set("east", "East"); // set key and value in Map
dMap.set("west", "West");

console.log(dMap.size); // 2, We can get size of Map
dMap.has("east"); // true, check key is part of Map
dMap.delete("east"); // true, We can delete any key
dMap.clear(); // Clear all data form Map

WeakMap is just like a Map but the key of WeakMap is always an object, keys held weakly, and also size and clear will not work for WeakMap.

Set, WeakSet

A Set is just like a JavaScript Array but more powerful as compared to a JavaScript regular Array; in the set, a Set always add unique value.



const dSet = new Set();
dSet.add("East"); // add value in set
dSet.add("West");

console.log(dSet.size); // 2, We can get size of set
dSet.has("East"); // true, check key is part of set
dSet.delete("East"); // true, We can delete any key
dSet.clear(); // Clear all data form Set

WeakSet is also the same as Set but The WeakSet object lets you store weakly held objects in an array.

for-of loop

Es6 introduces a for-of loop for us we can use these loop elements as well as indices.


// getting array elements
for (const el of ['one', 'two']) {
  console.log(el);
}
// Output:
// 'one'
// 'two'

// getting array indices
for (const k of ['one', 'two'].keys()) {
  console.log(k);
}
// Output:
// 0
// 1

// getting indices and elements both
for (const [k, e] of ['one', 'two'].entries()) {
  console.log(k);
}
// Output:
// 0, 'one'
// 1, 'two'

Classes

Class is a blueprint of an object. Like we are creating a Student blueprint


class Student { 
	constructor(name, rollNo) { 
		this.name = name;
		this.rollNo = rollNo;
	 }
}
var stu = new Student("XYZ", 1)

console.log("My name is", stu.name ," and my roll number is ", stu.rollNo);

// Output:
// My name is XYZ  and my roll number is  1

Function Rest Parameter


function add(…args) {
	console.log(args);
} 

console.log(add(1, 2, 3, 4)); // 1, 2, 3, 4

Default Parameters


function multiply(a, b = 2) {
	return a * b;
}

console.log(multiply(3)); // 6
console.log(multiply(3, 5)); // 15

Arrow Functions

The arrow function is very useful for two reasons first it reduces the code size and can use surrounding this.


const arr = [1, 2, 3];
const squares = arr.map(x => x ** 2); // [2, 4, 9]


// second case problem
var obj = {
	name: "Test",
	getName: function() {
		setTimeout(function() {
			console.log(this.name);
		});
	}
};

obj.getName(); // undefined

Inside setTimeout this is a window object and we need to bind this inside the setTimeout function but inside the arrow functions no to bind this to the setTimeout function.

var obj = {
	name: "Test",
	getName: function() {
		setTimeout(() => {
			console.log(this.name);
		});
	}
};

obj.getName(); // Test

Promises


var promise = new Promise(function(resolve, reject) {
    var x = -2;
    
    if (x < 0) {
        reject("Negative numbers are not allowed.");
    } else {
        resolve("Successful")
    }
});
 
promise.then(
    function(result) { console.log(result) },  
    function(error) { console.log(error) } 
);

// Negative numbers are not allowed.


About the Author: Pankaj Bisht