The latest version of JS is ECMA-Script 6.0 released in 2015. Today, most of the leading browsers support ES6 but we still have to transpile the source code of our app to ES5 which all of the browsers support. We use BabelJS library to transpile. If you have ever used CoffeeScript then you would understand where these these new changes are inspired from.

Table of Content

Be sure to try these features out in the online REPL. You can try ES6 in browser console like in the picture.

Browser Console

ES6 Features

Arrow operator

This operator => is exactly like you define a anonymous function in CoffeeScript. This supports both oneliner expressions & statements bodies or closure.

  a = [1,2,3,4,5];
  a.map(function (i){return i*2});
  //=> (5) [2, 4, 6, 8, 10]

In ES6, we do like

  a.map( i => i*2);
  //=> (5) [2,4,6,8,10]
  // Expression bodies
  var odds = evens.map(v => v + 1);
  var nums = evens.map((v, i) => v + i);

Lexical arguments

Its like you use * in function arguments in Ruby, where you could pass any number of arguments using a single argument.
Using this you are not required to specify argument to function calls.

  evenSeparator = function() {
    let evenItems = [];
    for (let item of arguments) {
      if (item % 2 == 0) evenItems.push(item);
    }
    return evenItems;
  };

  console.log(evenSeparator(1, 2, 16, 4, 5, 6, 8));

  //=> [2, 16, 4, 6, 8]

the arguments object is accessible inside functions. But they are not accessible inside functions defined using () =>{} construct. See example:

  evenSeparator = () => {
    let evenItems = [];
    for (let item of arguments) {
    	if (item % 2 == 0) evenItems.push(item);
    }
    return evenItems;
  };

  console.log(evenSeparator(1, 2, 16, 4, 5, 6, 8));

Error

  Uncaught ReferenceError: arguments is not defined

Class keyword like other OOP langs

ES6 allows you to define prototypes using class keyword unlike previous version where you used to create objects from objects. Though it seems like class based OOP, but its only a syntactic sugar for defining prototypes.

  class Animal{
    constructor(name){
      this.name = name
    }
    
    speak(){
      console.log("Hey I am " + this.name);
    }
  }

  class Dog extends Animal{
    constructor(name, owner){
      super(name);
      this.owner = owner;
    }
    
    speak(){
      console.log("Whoowoo!!: ");
      super.speak();
      console.log("My owner is: " + this.owner);
    }
  }

  pet = new Dog('Brian', 'Peter');
  pet.speak();

Console Output

  "Whoowoo!!: "
  "Hey I am Brian"
  "My owner is: Peter"

Tips
You will have to call the super constructor method in the first line of Sub-Classes. It cannot be in after any-other statements. But you can call any method keeping super as method receiver like in Dog#speak() method.


Meta-Programming : Dynamic object/properties definition

  options = function(){
    console.log("Hello");
  };

  obj = {
    // shorthand for options: options
    options,
    
    // defining dynamic methods ( a part of JS Meta-Programming)
    ["method_" + (() => 12)()]: 12
  }
  //=> Object {method_12: 12, options: function}
  
  obj.method_12
  //=> 12
  
  obj.options
  // function (){
  //   console.log("Hello");
  // }
  
  obj.options()
  //=> Hello

String Interpolation : Templating

Now, you don’t have to join two string objects using + (Plus) operator. You can just create a template and embed your variables inside the string like almonds in pudding.

  let names = ['Shiva', 'Peter', 'Ravi', 'Clark'];
  for(name of names){
    console.log(`The name is ${name}`);
  }

Output

  The name is Shiva
  The name is Peter
  The name is Ravi
  The name is Clark

You have noticed that we use back-tic char to define the string-templates.

Note
In Ruby we do Interpolation using #{var_name} construct.


Multiline string

Now you don’t have to concat strings to make it Multiline. Its much faster and not-annoying.

str = `This line starts here

       continues here 
       
       and
       
       Ends here`
  

De-structuring

Now JS natively supports pattern matching kind of construct.

  // list matching
  var [a, ,b] = [1,2,3];
  a === 1;
  b === 3;
  
  // Can be used in parameter position
  function g({name: x}) {
    console.log(x);
  }
  g({name: 5})
  //=> 5

De-structuring with defaults

While De-structuring there can be situations when expected data is missing and variable can remain undefined unknowingly. This is not a best case scenario; undefined is pain-in-the-@ss for developers.

  var [a = 'default'] = [];
  a === 'default';
  //=> true

What happens is, under unfavorable conditions, variable a is initialized with default data.

Functions with default arguments

This is most awesome feature which will eventually help you write more maintainable code. This will pay you a lot in a long run.

  summer = function({num1, num2, num3 = 10, num4 = 10}){
    return num1 + num2 + num3 + num4;
  }

  console.log(summer({num1: 2, num2: 2}));
  //=> 24
  
  console.log(summer({num1: 2, num2: 0, num4: 2}));
  //=> 14

* Modules

This is one of the key features which help you write reusable components. One can simply import components needed from different libraries and files in the same project.

In this we create several files hosting separate functions; we now need to use them in a file.

Note
To test this feature you may need babel support to transpile the code to ES5 because, browsers do not support this.

  // components/math.js
  export default function sum(num1, num2){
    return num1 + num2;
  };

  // Another way to that
  sub = (num1, num2) => {return num1 - num2} ;
  export sub;
  // components/string.js
  export default function concat(str1, str2){
    return str1 + str2;
  };

  find = (str, word) => {return str.indexOf(word)} ;
  export find;
  // app.js
  import adder, {sub} from 'components/math.js';
  import strAdder, {find} from 'components/string.js';

  console.log(adder(12, 12));
  //=> 24

See this for more info

Map + Set + WeakMap + WeakSet

Efficient data structures for common algorithms. WeakMaps provides leak-free object-key’d side tables.

  // Sets
  var s = new Set();
  s.add("hello").add("goodbye").add("hello");
  s.size === 2;
  s.has("hello") === true;

  // Maps
  var m = new Map();
  m.set("hello", 42);
  m.set(s, 34);
  m.get(s) == 34;

  // Weak Maps
  var wm = new WeakMap();
  wm.set(s, { extra: 42 });
  wm.size === undefined

  // Weak Sets
  var ws = new WeakSet();
  ws.add({ data: 42 });
  // Because the added object has no other references, it will not be held in the set

Reference

The purpose of this document is to help future-me to recall everything about ES6. In addition, I also wish to help you get hang of ES to get going in JS software development.

See this link to learn more.



Tags

JavaScript  ES6  Introduction  Tutorial  Learn Easier Way