ES6 Features





Today, I’m going to write a post on ECMAScript 6 major feature. In addition, I will provide a working example of each feature.

Const

Variables defined using const cannot be changed.

const pi = 3.14;
pi = 4.2;
console.log(pi);

Output:
Uncaught TypeError: Assignment to a constant variable.
at <anonymous>:2:4

Let

Till ES5 we have only global and function scope. However, ECMAScript 6 introduced a block level scope called ‘let’.

Example with var

function sampleDemo() {
 var i = 20;
 for(var i=0;i<10;i++){
   console.log(i);
 }
 console.log(i) // output 10; 
}

Example with ‘let’

function sampleDemo() {
 let i = 20;
 for(let i=0;i<10;i++){
  console.log(i);
 }
 console.log(i) // output 20; 
}

Arrow functions

Arrow functions are similar to normal functions. But, more expressive closure syntax.

let wish = (name) => {
console.log('Hello',name);
}
wish('commandsTech'); // output: Hello commandsTech

Template strings

Template strings help in the more clean way of writing long strings.

Destructuring

  • Array destructuring
    let stack = ['Angular', 'React', 'vue'];
    
    let [stack1, stack2, stack3 ] = stack;
    console.log(stack1); // output Angular
    console.log(stack2); // output React
    console.log(stack3); // output vue
  • Object destructuring
    let profile = {
    name : 'commandsTech',
    location : 'Hyd'
    }

    Before ES6 if you want to extract out variables

    let profileName = profile.name;
    let profileLocation = profile.location;

    Object destructuring helped us to do the achieve the same in just one line

    let { name: profileName , location: profileLocation } = profile;
    console.log(profileName); // ouput : commandsTech
    console.log(profileLocation); // output: Hyd
  • function destructuring
    Function destructuring simply the way in which parameters are passed. In addition, we can also pass default values for parameters.

    function sum({num1,num2,num3, num4=50}) {
    console.log(num1+num2+num3+num4)
    }
    
    sum({num1:10,num2:20,num3:30})
  • for-of loop

In for-each and for-in ‘continue’ ‘break’ and ‘return’ cannot be used so ES6 bought for-of loop.

var UIStack = ['Angular', 'react', 'vue', 'd3'];
for(technology of UIStack){
console.log(technology);
}
Output: Angular react vue d3

Modules

ECMAScript 6 that help us in importing and exporting modules. As a result,  we can use the function of one module in another module.
As shown in the below sample code methods or variables from one module can be imported into another.

// math.js
export pi = 3.17;
export sum = function (a,b) { return a+b;}

// sample.js
Import { pi, sum} from ‘/math.js’;
console.log(pi);
console.log(sum(2,3));




Maps

prior to ES6, the only way to store key and values is the object. ECMAScript 6 introduces a data structure called maps to store key-value pairs. The map provides a set method to pass data, get to retrieve, size to get map size, delete to remove a property, keys method to retrieve all keys and values to retrieve all values present in the map.

let scores = new Map([["dravid",50]]);

scores.set('sachin',90);
scores.set('sehwag',30);
scores.set('kohli',100);
scores.set('raina',20);

console.log(scores.get('dravid'));
console.log(scores.get('kohli')); // output 100;
console.log(scores.size);  // output 4
console.log(scores.has('sehwag')); // output true
scores.delete('raina');
console.log(scores.keys()); // output all keys
console.log(scores.values()); // output all values
scores.clear();

Sets

Similar to Map set is also a data structure but the set can store only values that are unique. Likewise sets also provide add, size, has and clear methods.

let scores = new Set();

scores.add('sachin');
scores.add('sehwag');
scores.add('kohli');
scores.add('raina');

console.log(scores); // output {"sachin", "sehwag", "kohli", "raina"}
console.log(scores.size); // output 4
console.log(scores.has('sachin')); // true
scores.clear();

Promises

Promise is introduced as part of ES6. Promise represents a value which may be available now, future or never. Above all Promise object is used for asynchronous operations, prior to promise call back are used to handle asynchronous operations

a promise can be in one of these states

  •  fulfilled
  • pending
  • rejected
    Promise methods
    all()
    All method is for handling multiple promises.

    var p1 = Promise.resolve(3);
    var p2 = 1337;
    var p3 = new Promise((resolve, reject) => {
      setTimeout(resolve, 100, 'foo');
    }); 
    Promise.all([p1, p2, p3]).then(values => { 
      console.log(values); // [3, 1337, "foo"] 
    });


    catch()
    Catch method to handle promise rejection

    p.catch(onRejected);
    p.catch(function(reason) {
       // rejection
    });


    then()
    then method on promise takes two functions as parameters.  first will be a success call back and second is a failure callback.




    p.then(function(value) {
       // fulfillment
      }, function(reason) {
      // rejection
    });


    race()
    race handles multiple promises but returns the promise that gets first resolve or reject.

    Promise.race([p1, p2]).then(function(value) {
    console.log(value);
    // Both resolve, but if p2 is faster then p2 output is executed
    });

    reject()
    Reject method returns a promise with a reason of rejected object.

    Promise.reject(new Error('fail')).then(function(error) {
      // not called
    }, function(error) {
      console.log(error); 
    });

    resolve()
    Resolve method returns a promise object with resolved value.

    Promise.resolve('Success').then(function(value) {
      console.log(value); // "Success"
    }, function(value) {
      // not called
    });

Classes & Inheritance

Classes introduced in ECMAScript simplified the creation of classes.

class Person {
 constructor(name,age){
  this.name = name;
  this.age = age;  
  }
  
 hello () {
   console.log('Hey',this.name, this.age);
  }
}

var p1 = new Person('vijay',25);

console.log(p1.name);
console.log(p1.age);
console.log(p1.hello());

Just like inheritance in java programming properties, and method of a class can be inherited to another using extends keyword.

class Animal{
constructor() {}
eat () {
console.log('Animal can eat');
}
}

class Lion extends Animal {
constructor() {
super();
this.name = 'Lion King';
}
who() {
console.log('Hey Im',this.name);
}
}

let t1 = new Lion();
console.log(t1); // Tiger
console.log(t1.who()); // Hey Im Lion King
console.log(t1.eat()); // Animal can eat




Leave a Reply

Your email address will not be published. Required fields are marked *