EcmaScript 6: a modern Javascript Language

Javascript is one of the most important language in existence nowadays. Every browser has a built-in Javascript interpreter, NodeJs as a server-side scripting language  is becoming more and more popular, and now it is even possible to use Javascript to build desktop app (Chrome app), mobile app (Cordova/React Native).

The current version of Javascript is ES5 but it lacks of some basic languages feature like: Class, Module separating, Block-scope, etc…  That why ES6 was introduced as an upgrade to current ES5. This blog will cover some basic usage of ES6 and how to apply ES6 to your project

Setup ES6 enviroment

To setup ES6, I prefer to use Babel as the Javascript compiler and Webpack. So the first thing we need to do is install these 2 package

npm install --save-dev babel-loader babel-core babel-preset-es2015
npm install –g webpack

Next we need to create Webpack config file webpack.config.js

module.exports = {
  entry: './entry.js', //This is link to the original file, change it
  output: {
    path: __dirname,
    filename: 'bundle.js';, //This is name for the compiled file, change it
  },
  module: {
    loaders: [
      { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader'}
    ]
  }
};

Next we need to create Babel config file .babelrc

{'presets': ['es2015']}

Finally we just need to execute the following command for Webpack to automatically compile our Javascript


webpack --watch

Basic ES6 syntax

Constant

const pi = 3.14
pi = 5 //error, cannot modify constant

Block-scoped variable

let x = 5;
{
  let x = 5 //This is a new scope
}
x === 5 //This is the old scope
let x = 6 //Error, re-declared variable

Arrow function

odds = evens.map(value => value + 1)
//equal to
odds = evens.map(function(value) { return value + 1; });

Default parameter

function foo(x, y=7, z=42) { return x + y + z }
foo(1) === 50

Template string

var name = 'Bob';
template = `Hello ${name}`; //This is equal to 'Hello Bob'

Module

//file lib/math.js
export function sum(x, y) { return x + y }
export var pi = 3.14
//file app.js
import {sum, pi} from  'lib/math'

Class

class Shape {
  constructor(x, y){
    this.x = x; //This is class attribute
    this.y = y; //This is class attribute
  }

  move(){ //This is a class method
    this.x = this.x + 1;
    this.y = this.y  + 1;
  }
}

Above is some of the usages and how to setup ES6 enviroment. You can find more usage and example from Babel page. Hope you find this is helpful.