ES6 is beautiful



One of my criticisms in the past when it comes to Javascript, is that it can get really messy, really quickly. That's before ES6 came along. ES6 has loads of great features, but I think the best part about ES6 is the brevity and clarity of its syntax.

I'm going to outline a few 'before and after' examples of my favourite ES6 features.

Variable unpacking

// ES5
var user = this.props.user,  
    post = this.props.post;

Becomes...

// ES6
const { user, post } = this.props;  

Short hand anonymous functions

// ES5
return (function(dispatch) {  
  return dispatch(myAction())
});
// ES6
return ((dispatch) => {  
  return dispatch(myAction());
});

Hmm, that's cool, but it's not that much different. But wait, we can condense that even further...

// ES6
return dispatch => {  
  return dispatch(myAction());
}

Or better still...

// ES6
return dispatch => dispatch(myAction());  

 Spread operator

// ES5
var arr1 = [1, 2, 3];  
var arr2 = [4, 5, 6];

Array.prototype.push.apply(arr1, arr2);  

Becomes...

// ES6
let arr1 = [1, 2, 3];  
let arr2 = [4, 5, 6];

arr1.push(...arr2);  

Default parameter values

// ES5
var user = function(state) {  
  if (state === undefined) {
    state = {
      name: 'Ewan'
    };
  }

  console.log(state.name);
};

Now in ES6...

// ES6
const user = (state = { name: 'Ewan' }) => {  
  console.log(state.name);
}

What a joy to use!

Now a feature I use loads, especially when building react components.

Template literals

// ES5
var name = "Ewan";  
console.log("Hello, my name is " + name);  
// ES6
let name = "Ewan";  
console.log(`Hello, my name is ${name}`);  

So much cleaner!

Array element finding

// ES5
var names = ["Ewan", "Fleabag", "Sam", "Caddy"];  
var res = names.filter(function (name) { return name === "Sam"; })[0];

console.log(res);  

becomes...

// ES6
let names = ["Ewan", "Fleabag", "Sam", "Caddy"];  
let res = names.find(name => name === "Sam");

console.log(res);  

As you can see from those examples, Javascript has come along way in ES6, not just in terms of new features, but the syntax itself has matured and become even more of a joy to work with!

That being said, ES6 isn't widely adopted yet, and many browsers don't support it yet, but there's a cool project, called babel which will transpile your ES6 code, into ES5 code, so you can start using ES6 today!