ES6 tutorial - A Quick guide

Learn ES6 in 10 minutes by practice. Today let’s learn ES6 or ES2015 features. ES6 is the next version of JavaScript with so many nice features and syntactic sugar. Right now you can find this in Node or IOjs and some latest web browsers including IE Edge.
I said some unfortunately by the time writing this post there are no browser or Nodejs are supporting this all futures. If you are using node.js you can see the features not available by running this command below.

node --v8-options | grep "in progress"  

I have been using ES6 form past 6 months. I should say it made my coding life a lot easier. Thought it's not yet implemented in all browser we don’t need to worry about it because we can use the tool called babel to transpile our code. You will write you code in ES6 standards and the babel will convert you code into es5. So that it will execute in all browsers (old, new all). In another hand, we have this amazing tool called jspm. Basically, jspm is a JavaScript package manager but it will do a lot more stuff them managing JavaScript packages. We will use babel with jspm to get es6 module support. Because jspm uses System.js which is actual module implementation for es6.

Setup

If you are not interested to do this you can skip it and use online REPL at http://babeljs.io/repl/ or Let’s just setup few things before you start. I hope you already have node or iojs installed in your system. If not please install them. Then install jpsm and jspm-server by using the following command on your command prompt or terminal.
npm i -g jspm jspm-server –g We are installing them as a global package because we may use them in other projects as well. Once you are done with installing go to the directory in command prompt where you want to have your code and type.
npm init And answer all questions. Once you are done you will see a package.json in your folder. Now type
jspm init –p Use the default settings just press enter for all questions. This will download all jspm required packages and creates config.js file which will useful for creating production code by jspm. Now open your package.json and add the following code in it.

  "start":"jspm-server" 

Finally, you package.json should look like this.

package.json

{
  "name": "es6-tutorial",
  "version": "1.0.0",
  "description": "es6 features ",
  "main": "app.js",
  "scripts": {
    "start":"jspm-server",
    "test": "karma test"
  },
  "jspm": {
    "devDependencies": {
      "babel": "npm:babel-core@^5.8.24",
      "babel-runtime": "npm:babel-runtime@^5.8.24",
      "core-js": "npm:core-js@^1.1.4"
    }
  },
  "author": "Dimpu Aravind Buddha <buddhaaravind@gmail.com> (http://techumber.com)",
  "license": "ISC"
}

Create index.htm and app.js file in the same directory and add following to you index.html

index.html

<!DOCTYPE html>  
<html lang="en">  
  <head>
    <meta charset="utf-8">
    <meta content="IE=edge" http-equiv="X-UA-Compatible">
    <meta content="width=device-width, initial-scale=1" name="viewport">
    <title>Es6 tutorial</title>
    <script src="./jspm_packages/system.js" type="text/javascript"></script>
    <script src="./config.js" type="text/javascript"></script>
  </head>
  <body>
    <h1 style="text-alignt:center">Es6 tutorial</h1>
    <script type="text/javascript">
      System.load('./app.js');
    </script>
  </body>
</html>  

Now go to your command prompt and type

npm start  

If you did everything correct you should see the web page in your browser in general at http://127.0.0.1:8080/ location. Now you are ready to write some code. Now let’s start to play.

1) Let

If you had work JavaScript before you must have faced a problem with JavaScript variables sometimes. Let’s take an example.

var lang =  "php";  
for(;true;){  
  var lang = "js";
  console.log(lang); //expect js
  break;
}
console.log(lang); //expect php  

In your console you will see both will log js. Now by using ES6 let.

"use strict";
let lang =  "php";  
for(;true;){  
  let lang = "js";
  console.log(lang); //expect js
  break;
}
console.log(lang); //expect php

You will get js, PHP in your console. So if you see basically let allow blocked scope. Of course, you can still use var if you want.

2)const

The const keyword is to create constants in your code. If you think it doesn't make a scene to change the Math PI value right? So when you put const before any variable we are not allowing that variable to change at any place in your program.

"use strict";
const PI = 3.41;  
PI = 2.3;  

3) Class

When I first time heard about the class in JavaScript I really didn't like it I thought es6 ruining the JavaScript's prototype feature. But I was wrong class are just a syntactic sugar over JavaScript prototype. ES6 also give this nice way to implement inheritance once class form another which is also just same as prototypical inheritance. Let's first see few new things in es6 class.

"use strict";
class Person{  
  /**
   * initiate anythin you want here
   */
  constructor(){
    this._name = 'aravind';
    this._age  = '25';
  }
  /**
   * get _name
   */
  get name(){
    return this._name;
  }
  /**
   * set _name
   */
  set name(name) {
    this._name = name;
    this._first_name = name.split(' ')[0];
    this._last_name = name.split(' ')[1];
  }
  /**
   * a static function
   */
  static nameToUpper(my_name){
    return my_name.toUpperCase();
  }
}

let p = new Person();  
p.name = 'Aravind Buddha'; // this will triger "set name" function  
console.log(p._name);  
console.log(p._first_name);  
console.log(p._last_name);

//calling static function
console.log(Person.nameToUpper('aravind'));  

In this we have the class person we will use constructor to initialize any variable or to call some other functions when we create a new object for that class.
Take a look at the set and get function. These two function confused me a little bit at first but after playing with them a bit I totally loved it. So do you I think.
In above example. Let say we want to create firstname and lastname based on the name we were given. Traditionally we have to set the name on _name property and then we have to call the function to split the full name and store them in two different properties. But by using ES6 we set we are only setting the name with dot(.) Operator we will set only on name property the set function take care of rest by having our split code in it. So, basically set and get act as formatters while when we set and retrieve properties from that class. Thought set and get are functions we will treat them as properties of that class. That’s why we will call them as

p.name = "Aravind";  

Also, you can have a static function. You will call your static function by using Class name itself instead of the class instance.

Inheritance

Es6 made inheritance so easy. Let’s see some code.

class Student extends Person{  
  constructor(){
    /**
     * to make sure everthing initiated in parent class
     */
    super();
  }
}

let p = new Student();  
p.name = 'Aravind Buddha'; // this will triger "set name" function  
console.log(p._name);  

Here we are inheriting the Person class into Student class. Now, You can use all properties and functions form Person class inside your Students class. Use super to call parent constructor if you have any initiations in the parent class. Remember thought we are using classes. It’s just a syntactic sugar over JavaScript prototypes we are still using JavaScript prototypes behind the science.

4) Arrow functions

These are one of my most favorite feature in ES6. Let's write a callback function in both es5 and es6 to see the difference.

"use strict";
//es5 code
var avengers = ['tony','steve','bruce','thor'].filter(function(aven){  
  return aven != 'thor'
});
console.log(avengers);  
//same in es6
let avengers = ['tony','steve','bruce','thor'].filter((aven)=> aven != 'thor' );  
console.log(avengers);  

You can see how easy it is to write call back function in es6. This is good but the best parts comes when you use it in lexical this Whenever you want to use this inside some other function you need to create an intermediate variable like

var self = this  

but now you don't need it. See the example below.

use strict";  
class Avenger{  
  constructor(){
    this.who = 'tony';
  }
  says(){
    setTimeout(()=>{
      console.log(this.who+' says Rock and roll');
    },1);
  }
}
let tony = new Avenger();  
tony.says();  

Simple. Isn’t it?

5) Template Strings

We also call them as interpolate strings. Till now are using third party libraries like mustache.js and handlebars.js to implement sting interpolation in our application but new es6 comes with built-in string interpolation?

//es5
var avenger = "tony";  
var says = "Sometimes you gotta run before you can walk.";  
console.log(avenger+" says "+says);  
//es 6
"use strict";
let avenger = "tony";  
let says = "Sometimes you gotta run before you can walk.";  
console.log(`${avenger} says ${says}`);  

We can also use template strings as multi-line strings. Like this.

//es5
var html = '<div class="form-group">'+  
  '<label class="sr-only" for="">label</label>'+
  '<input type="email" class="form-control" id="" placeholder="Input field">'+
 '</div>';
console.log(html);  
//es6
'use strict';  
let html = `<div class="form-group">  
   <label class="sr-only" for="">label</label>
   <input type="email" class="form-control" id="" placeholder="Input field">
  </div>`;
  console.log(html);

6) DE-structuring

Take a look at below example first.

'use strict';  
let tony = 'tony';  
let says = 'Sometimes you gotta run before you can walk.';  
let avanger = {tony,says};  
console.log(avanger);//Object {tony: "tony", says: "Sometimes you gotta run before you can walk."}  

So basically it simplifies the way you write you code. You can do it in another way around also.

use strict';  
let avenger = { tony:'tony',says:'Sometimes you gotta run before you can walk.'};

let {tony,says} = avenger;  
console.log(tony);  
console.log(says);  

7) Modules

There are two third party popular JavaScript module loaders (AMD, CommonJs) available right now. ES6 Implements the modules loading using System.js which combines both AMD and Commonjs features. ES6 module loading is almost same as Node.js module loader. Let’s create Person Class and export it to make it available for in other modules.

Person

class Person{  
  //some Code here
}
export default Person;  

App

'use strict';  
import Person from './Person';  
let p = new Person();  

Here we are importing the Classes which we exported in Person.js . You don’t need to give .js ext. while importing.

7) Promises

Again, we already have this by using third party libraries. For example, see https://github.com/kriskowal/q one of the famous promises library which I also being used in angular.js

function task(my_task){  
  return new Promise((resolve,reject)=>{
      setTimeout(function(){
        if(my_task == 'find loki'){
        resolve();
      }else{
        reject();
      }  
    },2000);
  });  
}
// this will accept 
task('find loki').then(()=>{  
  console.log("Thor: I'm on it.");
}).catch(()=>{
  console.log("Thor: It's my brother I can't do it.");
});

//this will reject
task('kill loki').then(()=>{  
  console.log("Thor: I'm on it.");
}).catch(()=>{
  console.log("Thor: It's my brother I can't do it.");
});

then will be executed when its success, catch will be executed if it's failed.

what next?

Above are the only features I used in my daily work but if you want to see more. Go to http://babeljs.io/docs/learn-es2015/

Conclusion

Even though some features already exits with third party library's it feels good to have those features native to JS now. After using ES6 in last 4 months I should say it's amazing. We all should start writing tomorrow's code toady so that when all browsers implement es6 we don't need to change any code.
What do you think?

Get posts by email

Like what you're reading? Get these posts delivered to your inbox.