ES6 VS ES5 Learnings

Here I have Shown some of the major advantages of ES6 . No bullshit. Direct Examples. Thank you

Lecture 1: let and const

There are three major differences between ES5’s var and ES6’s let & const.

• The major difference is that var declares a function scope variable and let and const declares a block scope variable
• In var, if you use a variable without declaring then it assign undefined to that variable where in let & const it throws an error.
• You can change the value of a variable defined by var but in const that is not possible.

Examples:

//ES5
var name5 = 'Jane Smith';
var age5 = 23;
name5 = 'Jane Miller';
console.log(name5);  
//Output: Jane Miller

//ES6
const name6 = 'Jane Smith';
let age6 = 23;
name6 = 'Jane Miller';
console.log(name6);
//Error

//ES5
function driversLicence5(passedTest) {  
    if (passedTest) {
        console.log(firstName);
        var firstName = 'John';
        var yearOfBirth = 1990;
    }
     console.log(firstName + ', born in ' + yearOfBirth + ', is now officially allowed to   drive a car.');
}

driversLicence5(true);
// Output: John born in 1990 is now officially allowed to drive a car.

NOTE: if we write the same code with using let and const then this will throw an error as the scope of firstname and yearOfBirth variable then will be limited to the if block only. So to make this code work we have to write like below.

//ES6
function driversLicence6(passedTest) {
    //console.log(firstName);
    let firstName;
    const yearOfBirth = 1990;
    
    if (passedTest) {
        firstName = 'John';
    } 
    console.log(firstName + ', born in ' + yearOfBirth + ', is now officially allowed to drive a car.');
}
driversLicence6(true);

//ES5
var i = 23;
for (var i = 0; i < 5; i++) {
    console.log(i);
}
console.log(i); 
// Output: 0 1 2 3 4 5


//ES6
let i = 23;
for (let i = 0; i < 5; i++) {
    console.log(i);
}
console.log(i);
//Output: SyntaxError: Identifier 'i' has already been declared

Lecture 2: Blocks and IIFEs

In ES5 you need an IIFE to create private variables but in ES6 variables declared using let and const are not accessible outside of a block. Let’s see this by an example.

//ES6
{
    const a = 1;
    let b = 2;
    var c = 3;
}
//console.log(a + b); 
//if we uncomment above part it will throw an error
console.log(c); //Output: 3

//ES5
(function() {
    var c = 3;
})();

console.log(c);

/*This code throws an error as the variable inside IIFEs can not be accessed outside of the scope*/

Lecture 3: Strings

In ES5, String concatenation is done using ‘+’ operator which is quite confusing and forgetting a ‘+’ is common. So ES6 comes with a handy feature that is known as ‘String Literals’. To use this we have to use backticks ( ` ) instead of single or double quotes. Literals are defined by ${something-to-print}. Let’s see how to use that by comparing ES5 way and ES6 way.

let firstName = 'John';
let lastName = 'Smith';
const yearOfBirth = 1990;

function calcAge(year) {
    return 2016 - year;
}

//ES5
console.log('This is ' + firstName + ' ' + lastName + '. He was born in ' + yearOfBirth + '. Today, he is ' + calcAge(yearOfBirth) + ' years old.');

//ES6
console.log(`This is ${firstName} ${lastName}. He was born in ${yearOfBirth}. Today, he is ${calcAge(yearOfBirth)} years old.`);

Not only this, ES6 also introduces some new functions and properties for string types. We will see this by an example.

let firstName = 'John';
let lastName = 'Smith';
const n = `${firstName} ${lastName}`;
console.log(n.startsWith('j')); //false
console.log(n.endsWith('Sm')); //false
console.log(n.includes('oh')); //true
console.log(`${firstName} `.repeat(3)); //John John John
• startsWith(): Returns true if string starts with the argument passed otherwise false.
• endsWith(): Returns true if string ends with the argument passed otherwise false.
• includes(): Returns true if string contains the argument passed otherwise false.
• repeat(): Returns the caller string no of times in the argument.

Lecture 4: Arrow Functions

Arrow functions are shorter version of function with some major changes. Which we will see by examples.

const years = [1990, 1965, 1982, 1937];

//ES5
var ages5 = years.map(function(el) {
    return 2016 - el;
});
console.log(ages5);

//ES6
let ages6 = years.map(el => 2016 - el);
console.log(ages6);

//Some more examples

ages6 = years.map((el, index) => `Age element ${index + 1}: ${2016 - el}.`);
console.log(ages6);

ages6 = years.map((el, index) => {
    const now = new Date().getFullYear();
    const age = now - el;
    return `Age element ${index + 1}: ${age}.`
});
console.log(ages6);


The this keyword works differently in arrow functions let us understand by an example.

//ES5
var box5 = {
    color: 'green',
    position: 1,
    clickMe: function() {
            var self = this; 
            document.querySelector('.green').addEventListener('click', function() {
            var str = 'This is box number ' + self.position + ' and it is ' + self.color;
            alert(str);
        });
    }
}
box5.clickMe();

//ES6
const box6 = {
    color: 'green',
    position: 1,
    clickMe: function() {
            document.querySelector('.green').addEventListener('click', () => {
            var str = `This is box number ${this.position} and it is  ${this.color}`;
            alert(str);
        });
    }
}
box6.clickMe();

There is a clear difference between the ES5 and ES6 version, As in ES5 you can not access the other properties like color and position by using this keyword in callback function of event-listener that is why we store the this instance in self variable where in ES6 it can be accessed via this keyword which is a major advantage.

Lecture 5: De-structuring

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. Let’s see some examples.

// ES5
var john = ['John', 26];
var name = john[0];
var age = john[1];

// ES6
const [name, age] = ['John', 26];
console.log(name);
console.log(age);

It’s not limited to only this we can even use it for assignments like the following example.

const obj = {
    firstName: 'John',
    lastName: 'Smith'
};

const {firstName, lastName} = obj;
console.log(firstName);
console.log(lastName);

The above example will throw an error that firstname is already defined so we can solve this by assigning specific property to specific variable by following way.

const {firstName: a, lastName: b} = obj;
console.log(a);
console.log(b);

We can even use this to return more then one values from a function.

function calcAgeRetirement(year) {
    const age = new Date().getFullYear() - year;
    return [age, 65 - age];
}

const [age2, retirement] = calcAgeRetirement(1990);
console.log(age2);
console.log(retirement);

Lecture 6: Arrays

In ES6 there are new features are implemented to making it more convenient. There are major two things first is the from() method for creating array from any other linear structures for example: nodelists. Another major feature is introduction of for..of loop which we will see by an example. The examples are given below.

const boxes = document.querySelectorAll('.box');

//ES5
var boxesArr5 = Array.prototype.slice.call(boxes);
boxesArr5.forEach(function(cur) {
    cur.style.backgroundColor = 'dodgerblue';
});

//ES6
const boxesArr6 = Array.from(boxes);
boxesArr6.forEach(cur => cur.style.backgroundColor = 'dodgerblue');

In above example in ES5 there is no predefined function for creation of array so we have to use the slice method and call it with the var we want to make array of. In ES6 there is from() method of Array object which directly converts any linear list to an Array which is more convenient as compared to ES5.

//ES5
for(var i = 0; i < boxesArr5.length; i++) {
    if(boxesArr5[i].className === 'box blue') {
        continue;
    }
    boxesArr5[i].textContent = 'I changed to blue!';
}

//ES6
for (const cur of boxesArr6) {
    if (cur.className.includes('blue')) {
        continue;
    }
    cur.textContent = 'I changed to blue!';
}

In map() and forEach() methods or loops we can not use the continue and break statements. So to use that in ES5 we have to use for loop. In ES6 we can do that by using for..of loop, which is pretty easy.

There are other features as well which will can make our code more readable and short. Methods like findIndex() and find() are one of them. The examples are shown below.

//ES5
var ages = [12, 17, 8, 21, 14, 11];

var full = ages.map(function(cur) {
    return cur >= 18;
});
console.log(full);

console.log(full.indexOf(true));
console.log(ages[full.indexOf(true)]);

//ES6
console.log(ages.findIndex(cur => cur >= 18));
console.log(ages.find(cur => cur >= 18));
• find(): finds an element accepts a callback function as an argument.
• findIndex(): finds an index of the element. Accepts a callback function as an argument.

Lecture 7: Spread Operator

ES6 introduced a very cool operator which can be used to expand the elements of the array without using any loop or methods. It is a unary operator and the syntax is

...[arrayname]

The example is as follows.

function addFourAges (a, b, c, d) {
    return a + b + c + d;
}

var sum1 = addFourAges(18, 30, 12, 21);
console.log(sum1);

//ES5
var ages = [18, 30, 12, 21];
var sum2 = addFourAges.apply(null, ages);
console.log(sum2);

//ES6
const sum3 = addFourAges(...ages);
console.log(sum3);

//Example 2

//ES6
const familySmith = ['John', 'Jane', 'Mark'];
const familyMiller = ['Mary', 'Bob', 'Ann'];
const bigFamily = [...familySmith, 'Lily', ...familyMiller];
console.log(bigFamily);

//Example 3

//ES6
const h = document.querySelector('h1');
const boxes = document.querySelectorAll('.box');
const all = [h, ...boxes];

Array.from(all).forEach(cur => cur.style.color = 'purple');

Lecture 8: Rest Parameters

In Javascript, If you don’t know how many arguments a function will have you can use rest parameters and still call the function. It’s cool right let’s see how we do this it differently in ES6.

//ES5
function isFullAge5() {
    //console.log(arguments);
    var argsArr = Array.prototype.slice.call(arguments);
    argsArr.forEach(function(cur) {
        console.log((2016 - cur) >= 18);
    })
}

isFullAge5(1990, 1999, 1965, 2016, 1987);

//ES6
function isFullAge6(...years) {
    years.forEach(cur => console.log((2016 - cur) >= 18));
}

isFullAge6(1990, 1999, 1965, 2016, 1987);

In ES5 you have to access the arguments object to access the rest arguments and that returns a list which then we have to convert it into the array and then we can use that.

In ES6 you can use the spread operator to tell the function that i don’t know how many arguments this function is gonna accept. Which is very convenient and it returns array directly as you can see in example years becomes an array.

//Example2

//ES5
function isFullAge5(limit) {
    var argsArr = Array.prototype.slice.call(arguments, 1);

    argsArr.forEach(function(cur) {
        console.log((2016 - cur) >= limit);
    })
}

isFullAge5(1990, 1999, 1965, 2016, 1987);

//ES6
function isFullAge6(limit, ...years) {
    years.forEach(cur => console.log((2016 - cur) >= limit));
}

isFullAge6(16, 1990, 1999, 1965, 2016, 1987);
      Lecture 9: Default Parameters

Default parameters are the arguments which has some default value. If you don’t pass any value in those parameters then it takes the default value.

//ES5
function SmithPerson(firstName, yearOfBirth, lastName, nationality) {
    lastName === undefined ? lastName = 'Smith' : lastName = lastName;

    nationality === undefined ? nationality = 'american' : nationality = nationality;

    this.firstName = firstName;
    this.lastName = lastName;
    this.yearOfBirth = yearOfBirth;
    this.nationality = nationality;
}

//ES6
function SmithPerson(firstName, yearOfBirth, lastName = 'Smith', nationality = 'american') {
    this.firstName = firstName;
    this.lastName = lastName;
    this.yearOfBirth = yearOfBirth;
    this.nationality = nationality;
}

In ES5, We have to do this with some conditional statements and check if the argument is undefined or not. If it is undefined then assign some value.

In ES6, We can just assign some value with the arguments at the time of defining the function just like in above example. It is that simple.

Lecture 10: Maps

This is the whole new feature introduced in ES6. If you have worked on JAVA and other object oriented languages then probably you know the concept of Maps. If you are new do not worry, Maps are just key:value pairs which makes it easy to define a structure. How ? Let’s see by an examples and see the cool methods that map has.

const question = new Map();
question.set('question', 'What is the official name of the latest major JavaScript version?');
question.set(1, 'ES5');
question.set(2, 'ES6');
question.set(3, 'ES2015');
question.set(4, 'ES7');
question.set('correct', 3);
question.set(true, 'Correct answer :D');
question.set(false, 'Wrong, please try again!');

console.log(question.get('question'));
console.log(question.size);

if(question.has(4)) {
    question.delete(4);
}

for (let [key, value] of question.entries()) {
    if (typeof(key) === 'number') {
        console.log(`Answer ${key}: ${value}`);
    }
}

const ans = parseInt(prompt('Write the correct answer'));
console.log(question.get(ans === question.get('correct')));
question.clear();

In above example you can see you can create a map by just using the new operator.

To add key:value pairs in map you have to use the set() method which has two arguments one for key and the other for value.

To check if the map contains a key or not you can use the has() method.

To get the length of key:value pairs a map has then you can use the length property of the map.

To remove a key:value pair you just have to call the delete() method with a key as an argument and it is done.

The entries() method returns all key:value pairs which you can use to apply loop and perform a function. Don’t forget to use destructuring.

If you wanna clear all entries from a map just use clear() method for this.

Lecture 11: Classes

In ES5, We were using function constructor for creating objects. But, ES6 brought a pretty new concept which is pretty old in all object oriented languages is classes.
Let’s see the difference.

//ES5
var Person5 = function(name, yearOfBirth, job) {
    this.name = name;
    this.yearOfBirth = yearOfBirth;
    this.job = job;
}

Person5.prototype.calculateAge = function() {
    var age = new Date().getFullYear - this.yearOfBirth;
    console.log(age);
}

var john5 = new Person5('John', 1990, 'teacher');

//ES6
class Person6 {
    constructor (name, yearOfBirth, job) {
        this.name = name;
        this.yearOfBirth = yearOfBirth;
        this.job = job;
    }
    calculateAge() {
        var age = new Date().getFullYear - this.yearOfBirth;
        console.log(age);
    }
    static greeting() {
        console.log('Hey there!');
    }
}

const john6 = new Person6('John', 1990, 'teacher');
Person6.greeting();

Both code does the same thing but ES6 version makes it more clear and readable and yeah static methods which we can call by class name and which has only a single copy in the memory is new addition to ES6.

Lecture 12: Inheritance

In ES5, We have to use the object.create() method for clearing yes that we are using inheritance in our code. In ES6, We just have to use the extends keyword let’s see how?

//ES5
var Person5 = function(name, yearOfBirth, job) {
    this.name = name;
    this.yearOfBirth = yearOfBirth;
    this.job = job;
}

Person5.prototype.calculateAge = function() {
    var age = new Date().getFullYear() - this.yearOfBirth;
    console.log(age);
}

var Athlete5 = function(name, yearOfBirth, job, olymicGames, medals) {
    Person5.call(this, name, yearOfBirth, job);
    this.olymicGames = olymicGames;
    this.medals = medals;
}

Athlete5.prototype = Object.create(Person5.prototype);
    Athlete5.prototype.wonMedal = function() {
    this.medals++;
    console.log(this.medals);
}

var johnAthlete5 = new Athlete5('John', 1990, 'swimmer', 3, 10);

johnAthlete5.calculateAge();
johnAthlete5.wonMedal();

In above code as you can see Athlete5 class is inheriting the Person5 class. For performing inheritance we have to perform following steps.

• Call the function constructor of base class into the child class. As we can see in the above example.
  
  Person5.call(this, name, yearOfBirth, job);
  
• Tell the javascript that child class is inheriting base class in above example.
  
  Athlete5.prototype = Object.create(Person5.prototype);
  
does the same thing.

Let’s see how this can be done in ES6.

//ES6

class Person6 {
    constructor (name, yearOfBirth, job) {
        this.name = name;
        this.yearOfBirth = yearOfBirth;
        this.job = job;
    }

    calculateAge() {
        var age = new Date().getFullYear() - this.yearOfBirth;
        console.log(age);
    }
}

class Athlete6 extends Person6 {
    constructor(name, yearOfBirth, job, olympicGames, medals) {
        super(name, yearOfBirth, job);
        this.olympicGames = olympicGames;
        this.medals = medals;
    }
    wonMedal() {
        this.medals++;
        console.log(this.medals);
    }
}

const johnAthlete6 = new Athlete6('John', 1990, 'swimmer', 3, 10);

johnAthlete6.wonMedal();
johnAthlete6.calculateAge();

We did the exact same thing by less confusing code with ES6.

• We used extends keyword with Athlete6 class to tell javascript that we are inheriting the Person6 class.
• We used super keyword to call the constructor of the base class to make it less confusing.
H2
H3
H4
3 columns
2 columns
1 column
Join the conversation now
Logo
Center