ECMAScript 6 Part I - gpawade/gpawade.github.io GitHub Wiki

In ES6 has some very good new feature. We'll go through some of them in this bog.

Please refer http://jsbin.com/ziyedu/embed?html,js,console for running sample.

Constant

In ES6 has support for constant. Variable which declare with const cannot be reassigned new content. It's also known as "immutable variable".

// Declaration
const MY_VAR = "Constant value"

Block-Scope variable

//Legacy - without block-scope
var i=0, x=0, a=[11,22,33,44];
for (i = 0; i < a.length; i++) {
    x = a[i];
}
console.log(i,x); // OUTPUT => 4 44

//ES6 - with block-scope
let cnt=0, y=0, b=[11,22,33,44];
for (let cnt = 0; cnt < b.length; cnt++) {
    let y = b[cnt];
}
console.log(cnt,y); // OUTPUT => 0 0

Arrow Function

// legacy sample
var arr = [1, 2, 3, 4, 5];
var newArr = arr.map(function (v) { return v + 1; });

// In ES6
var newArr = arr.map(v=> v + 1)

Template Literal/String

var person = { name : 'john', id : 20283 };
var template = `Welcome ${person.name}, your id is ${person.id}`
console.log(template);

Modules / Export

Named Export
//calmodule.js
export function add(x, y){
       return x + y;
}

//OR
var add = function(x, y){
    return x + y;   
}

export { add };

Usage of module

import { add } from "calmodule"

add(2, 4);

Note - curly braces are required when variable you would like to import. calmodule will look the file called calmodule.js in current folder.

Returning multiple function
var add = function(x, y){
    return x + y;   
}
var sub = function(x, y){
    return x -y;   
}

export { add, sub };
Default export

A module can define one default export.

//mymodule.js
export default function(x, y){
    return x * y;
}

// usage in a.js
import a from "mymodule";  // No need to pass the curly brace here. Also we can give any name to variable.
a(3, 4);

Note - module can have both named & default export.

Classes

Definition
//Legacy - 
var Person = function(id, name){
    this.id = id;
    this.name = name;   
};
Person.prototype.display = function(){
    //method logic goes here
};

// In ES6
Class Person{
    constructor (id, name){
        this.id = id
        this.name = name   
    }
    display(){
        //method logic goes here   
    }       
}

In part II will look into more details in class.

⚠️ **GitHub.com Fallback** ⚠️