OneCompiler

ES5 Vs ES6 Javascript

504

ECMA script is a scripting language where it creates a standard for Javascript. The current version of ECMA script is ES6. In this post, I am going to explain to you changes available in ES6 version when compared to ES5.

Arrow Functions

Arrow functions are introduced in ES6. This makes code cleaner and brought more clarity in Javascript code.

Function in ES5 version


const square = funtion(number) {
  return number * number;
}

Function in ES6 version

/* if there is only a single parameter taken by the function then there is no need of parenthesis*/ 

const square = number => {
   return number * number
}

We can also make it more clear by removing the return keyword

//If there is a single line of code in the function then we can remove return keyword and curly braces
 
const square = number => number * number;

var vs let vs const

Before ES6 i.e. in ES5 var is the only way to declare variables. The issue with the var keyword is it is not block-scoped, it will be available throughout the function even if we declared it in a block.

For example

function start(){
 for(var i = 0; i < 5; i++){
   console.log(i);
 }
 console.log(i);
}

/*output is
1
2
3
4
5 */

If we see the output we can access the I variable outside the loop which is not expected behavior. I variable can be accessible outside the loop because var keyword is function-scoped. To resolve this issue let and const were introduced in ES6 which are block-scoped.

For example

function start(){
 for(let i = 0; i < 5; i++){
   console.log(i);
 }
 console.log(i);
}

// Returns error because I variable is declared as let which is block-scoped

The variable which we declared as const it cannot change in the code. const is also a block-scoped.

var color = "Red";
let productId = 123

// If we declare a variable in var it will be attached to the window object

Promises vs Callback

** Callbacks **: Callback is a function that we are going to call when the result of the asynchronous operation is completed.

console.log('after');
getProductDetails('12345', (err, productDetails) => {
  console.log(productDetails)
});
console.log('before');

function getProductDetails(productId, cb) {
  setTimeout(() => {
    console.log('Reading product details from database');
    cb(null, {'id': productId, 'name': 'Chocolate'});
  }, 2000);
}

/* Output of the above code is
   after
   before
   {'id': 12345, 'name': 'Chocolate'}*/

Promises:

A promise is an object ** which holds the eventual result of an asynchronous operation**. When we are creating a Promise object it will be in the pending state after completion of the asynchronous operation, It can be either fulfilled if there is no error or in the rejected state

console.log('after');
getProductDetails(1)
.then(productDetails => getImages(productDetails.name))
.then(productImages => getRecommendations(productDetails.name))
.then(Recommendations => console.log('Recommendations', Recommendations))
.catch(err => console.log(err));
  

function getProductDetails(id){
    return new Promise((resolve, reject) => {
        setTimeout(function(){
            resolve({'id': productId, 'name': 'Chocolate'});  
        
        },2000);

    })
    
}

function getImages(name){
    return new Promise((resolve, reject) => {
        setTimeout(function(){
            resolve({'id': productId, 'imageDetails': ['ImageURL1','ImageURL2']});  
        
        },2000);

    })
}

function getRecommendations(name){
    return new Promise((resolve, reject) => {
        setTimeout(function(){
            resolve({'id': productId, 'imageDetails': ['Product1','Product2']); 
        
        },2000);

    })
}

** Import and Export**

Import and Export syntax had changed in ES6.

Export a module in ES5 expression


var module = { foo: bar, y: function(){ console.log('Declaration in ES5') }}

module.exports = myModule;

In ES6 version

 
var module = { foo: bar, y: function(){ console.log('Declaration in ES6') }}

export default module;

Import a module in ES5 version

const module = require('./module')

In ES6


import module from ./module

** Spread Operator **

To clone an object to the other object in Javascript we use spread operator which was introduced in ES6.

Let's see differences to clone an object in ES6 and ES5

In ES5 version

const productDetails{
  productName: "colgate",
  description: "paste",
  price: "2.00$",
  imageURL: "url"
}

//if we want to clone the object
const another = {};
for(let key in productDetails) {
  another['key'] = productDetails['key']
}

** In ES6 **

const productDetails{
  productName: "colgate",
  description: "paste",
  price: "2.00$",
  imageURL: "url"
}

const another = {...productDetails};

//Using spread operator we can clone an object easily

** Object Destructuring **:

In ES5

var productName = 'colgate';
var price = 3 $;
var image = "ImageURL";

var obj = {productName: productName, price: price,image:image}

It is so easy to define a object with same names in ES6

var productName = 'colgate';
var price = 3 $;
var image = "ImageURL";

var obj = {productName, price, image}