Favorite ES6 Features

With ES6 standardized and popular transpilers like 6to5 making its emergence, I figure to list out some of my favorite ES6 features.

Arrow Function

Without a doubt, the arrow function is my favorite and probably one of the most commonly seen peppered around in github source code. It's pure syntactic sugar but it's simplicity in how it handles the clunkiness of the this keyword definitely makes this my favorite.

Before:

var User: {  
  name: "John",
  welcome: function() {
    var that = this;
    request.get(url, function(res) {
      that.name = res.name;
    });
  }
}

With ES6:

var User: {  
  name: "John",
  welcome: function() {
    request.get(url, res => this.name = res.name );
  }
}

Promises

There's a lot of libraries provide the promises functionality like Q, Bluebird and in AngularJS but I was hoping for a more native implementation to quiet all the naysayers in regards to callback hell. Finally, that day has come.

Before:

async1(function () {  
  async2(function () {
    async3(function () {
      async4(function () {
      })
    })
  })
})

With ES6:

var async1 = new Promise(function(resolve, reject) {  
  resolve(1);
});
var async2 = new Promise(function(resolve, reject) {  
  resolve(1);
});
var async3 = new Promise(function(resolve, reject) {  
  resolve(1);
});
var async4 = function() {console.log('async4');}

async1.then(nosync).then(async3).then(async4);

Let

Javascript has an uncanny valley effect for most developers coming from a C and Java background. It looks like Java but it doesn't behave like it. Most developers learn the hard way through hard to find bugs. One of the bugs that get most developers is scoping

Before:

for(var i=0; i<10; i++) {  
// some implementation
}

console.log(i);  
// 10;

With ES6:

for(let i=0; i<10; i++) {  
// some implementation
}

console.log(i);  
// i is not defined

Default parameters

Although I wasn't too fond of CoffeeScript (I prefer TypeScript), one feature I liked a lot about CoffeeScript was the ability to set default parameters. It was more declarative and reduced some plumbing when passing in parameters.

Before:

function handler(name, message) {  
  if (typeof name === "undefined") name = "John";
  if (typeof message === "undefined") message = "Hello";

  console.log(message + " " + name);
}

With ES6:

function handler(name = "John", message = "Hello") {  
  console.log(message + " " + name);
}

Destructuring

Once upon a time, I used to write in Perl. It was bashed for it's archaic and unreadable syntax (Write once, read never!). But quite honestly, if your developers had enough discipline, you can pump out pretty maintainable code. One such feature that I missed from Perl was Destructuring.

Before:

var list = [1,2,3];  
var a = list.shift();  
list.shift();  
var b = list.shift();  
console.log(a,b);  
// 1 3

With ES6:

var [a, , b] = [1,2,3];  
console.log(a,b);  
// 1 3
Comments powered by Disqus