ES6 – Compared with current Javascript

The current Javascript standard that is mostly supported are the 5th Edition (or ES5). In 2015, the 6th edition (ES6) is officially finalized, and ES7 is officially finalized in 2016. But, the browser support for ES5 is still incomplete, thus developers should not write their current javascript in ES5 standard. So, developers dreaming to write their code in ES6 (or ES7) should use a transpiler (e.g. Babel) to transpile their code into ES5 code.

ES6 brings many many cool features, which is highly useful for developers in writing their code more cleanly. In this post, it will be mentioned some really useful features added to ES6 which is not there in ES5.

Constants

Support for constants is added. Constants are immutable variables that cannot be re-assigned. In ES5, if you want to declare a variable, you can only use var. But in ES6, you can declare variable using keywords const or let. const for declaring constants, and let for declaring mutable variables.

// ES5
var PI = 3.14;
var currentNum = 2;

// ES6
const PI = 3.14;
let currentNum = 2;

 

Arrow functions

In ES5, you can create a function using keyword function. for example:

negatives = nums.map(function (n) { return -1 * n; });

In ES6, creating function is easier and “cooler”.

negatives = nums.map(n => -1 * n);

Using arrow function also give a more intuitive lexical this of current context.

// ES5
var self = this;
this.nums.forEach(function (v) { 
  self.fives.push(v);
});

// ES6
this.nums.forEach(v => {
  this.fives.push(v);
})

In ES5, if you want to use the caller’s thisinside the function, you should save that this to a variable. Because the this inside the function is the function’s context’s this, and not he outer’s this.

 

Conclusions

There is still many improvements over ES5. You can see them in various links on internet, e.g. http://es6-features.org/

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s