April 20, 2016

8 Awesome ES6 Features

by Caio Ribeiro Pereira

8 Awesome ES6 Features

In this post we will go over eight useful and interesting ECMAScript 6 (ES2015) features, such as classes, a feature that makes it easy for developers familiar with object oriented programming to start using JavaScript. We’ll also go over typical features inspired from functional programming languages, for instance arrow functions, let variables, etc.

Using const and let

After a long time using the keyword var to create variables and instantiate objects, the ES6 added two new useful keywords to handle with variables: const and let. Both are important features and it’s highly recommended to use them instead of the old var to avoid hoisting problems developer.mozilla.org/en-US/docs/Glossary/Hoisting. The main differences between const and let is that const allows you to create constants, and let to do the same as var, but it avoids hoisting problems. As a best practice, always use const to handle with immutable data, because it uses less memory than using let. Take a look at this example:

// creating a constant
const MAX = 10;  
// creating a variable
let value = 5;  
// you can't change the value of a constant
MAX = 5;  
// this change is allowed for `let` variables
value = 10;  
// creating a constant object
const obj = {};  
// You can only change object's attribute
obj.a = 10;  
// but you can't reassign new data here
obj = 100;  

Template Strings

The template string is a powerful feature, which allows you to interpolate data inside a string in an elegant way. To create a template string you need to create a string using grave accent, like in this example: This is a template string. If you need to interpolate data inside a string, you just need to use this syntax: ${data}. Take a look at the example below:

var name = "John Connor";  
console.log(`This is ${name} from the future!`);  

Another advantage of using template string is to write multiline strings without concatenate strings using + operator, now you can just break a line to do it:

var template = `  
<div>  
    <p>This is multline string</p>
</div>  
`;

Arrow Functions

In JavaScript it is very common to invoke functions, anonymous function and callback functions using the keyword function. The arrow function is a new feature which changes the way to create functions and the way they behave. By using the syntax sugar => we are creating a function that does not alter the this keyword and that does not create any special variables such as arguments. See some arrow examples:

// empty arrow-function
const foo() => {};  
// inline arrow-function
const add = (a, b) => {  
    a + b
};
// arrow-function
const compare = (a, b) => {  
    if (a > b) {
        return a;
    } else {
        return b;
    }
};
// arrow-function sharing context
const doSomething = (a, b) => {  
    this.a = a;
    // there is no need to use parenthesis when there is one argument
    const doNewThing = b => {
        this.b = b;
        return this.a + this.b;
    }
}

Spread Operators

The Spread Operator basically converts an array into arguments, it is very useful when you need to break array values to send them as parameters for a function or object constructors. To understand these feature, first let’s create a simple function below:

function add(a, b) => {  
    return a + b
};

Now, to invoke this function using an array elements as arguments, you just need to use this syntax: ...array, take a look:

const values = [1, 2];  
add(...values); // returns 3  

Method definition

If you need to create simple objects with some attributes and some functions, ES6 makes the process easier, for example:

var MyObject = {  
    a: 1,
    inc: function(b) {
        this.a += b;
    }
}

You can create methods instead object functions, eliminating the use of function keyword, have a look:

var MyObject = {  
    a: 1,
    // syntax sugar to create methods
    inc(b) {  
        this.a += b;
    }
}

Classes and inheritances

The class is one of the most awaited ES6′s features. Now you are able to create a class without the direct usage of the prototype objects in JavaScript. While using class you can include constructors, destructors, methods and inheritance. To see the differences between classes and prototype objects, we’re going to write the same Vehicle object using class and prototype. First, take a look at how we can create a Vehicle prototype object:

var Vehicle = function(name) {  
    this.name = name;
}

Vehicle.prototype.drive = function() {  
    console.log("Driving the ", this.name);
};

And now, we can write an expressive Vehicle object using ES6 class feature, see this example below:

class Vehicle {  
    constructor(name) {
        this.name = name;
    }
    drive() {
        console.log("Driving the ", this.name);
    }
}

Using classes, your code will be more expressive and cleaner. And what if we need to use inheritance? Using the OOP(Object-Oriented Programming) concepts, let’s create a Car class that extends all behavior of the Vehicle class. To do it, you just need to use the keyword extends to set who will be the parent class of this current class. And in the child class constructor you can use the super() method to call the parent class constructor when the current class is instantiated. See this example:

class Car extends Vehicle {  
    constructor(name, brand) {
        super(name);
        this.brand = brand;
    }
}

There is no new way to instantiate a class because it follows the same way you instantiate prototype objects too, so nothing is changed in this code below:

let car = new Car("A3", "Audi");  
car.drive();  

Default arguments

Default arguments is a very old feature, largely used in other languages like Ruby, Python, PHP, Java and others. Basically, it sets a default value for function arguments when these arguments do not have a value during a function invocation. In ES5 it was very normal to do this:

function Person(name, age) {  
    this.name = name || " John";
    this.age = age || 25;
}

It was very common to use the OR operator to simulate default value for these arguments. Now you can write less complex code using the default arguments:

function Person(name = "John", age = 25) {  
    this.name = name;
    this.age = age;
}

Object destructuring assignment

The shorthand value feature allows you to write less code when an object key and variable has the same name, for example:

// Creating a const name from this.obj.name
const {  
    name
} = this.obj;
// This is the same as writing: const name = this.obj.name;

You can apply destructuring when you create a new object as well:

const name = "John Connor";  
const obj = {  
        name
    } // This is the same of write: obj = { name: name }

Final Thoughts

In this post you learned a little bit about some useful features from ES6 (ECMAScript 6).

Today, not all features are compatible in the main browsers, even the latest version of Node.js still isn’t. To solve this problem, you can use Babel which fallbacks all main ES6 features to compatible ES5 for old browsers and Node.js too by transpiling the code. Moreover, if you want to learn more about new JavaScript features and how to use Babel to be able to run your application everywhere check our post about it here.