Learn ES6 in 20 minutes

Es6

Javascript is the most popular scripting language nowadays which works on ECMAScript specification. After the success of the ES5. Javascript 6 edition or ES6 is most demanding between programmers. So in this article, we will cove overview of es6 and cover most of the 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 with 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 create new binding for all itration 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],
wese = directions[1],
north = directions[2],
south= directions[3];

but es6 provide us with an elegant way to achieve this in proper meaner.


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 type in ES6. A map is just like a JavaScript Object (key-value pair) but more powerful as compare to a JavaScript regular object; in the Map, all value 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 just like a Map but the key of WeakMap always 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 compare to a JavaScript regular Array; in the set, 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 also the same as Set but The WeakSet object lets you store weakly held objects in an array.

for-of loop

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


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

// geting 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 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 setTimeout funtion but inside arrow funtion no to bind this to setTimout 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.


You May Also Like

About the Author: Pankaj Bisht