Web Development

8 Awesome ES6 Features

April 20th, 2016 | By Caio Ribeiro Pereira | 5 min read

Today, we will dive into eight useful and interesting ECMAScript 6 (ES2015) features, such as classes, to make it easy for developers familiar with object-oriented programming to start using JavaScript.

We will also explore typical features inspired by functional programming languages, for instance, arrow functions, let variables, etc.

1. 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 variables: const and let.

They are important features and it’s highly recommended to use them instead of the old var to avoid hoisting problems.

The main difference between const and let is that const allows you to create constants, and lets to do the same as var, but it avoids hoisting problems.

As a best practice, always use const to handle 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;


2. 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 the + operator, now you can just break a line to do it:

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


3. Arrow Functions

In JavaScript, it is very common to invoke functions, anonymous functions, and callback functions using the keyword function.

The arrow function is a new feature that 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 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;
    }
}


4. 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 features, first, let’s create a simple function below:

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


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

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


5. 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 of object functions, eliminating the use of function keywords, have a look:

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


6. 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 the 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. 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();


7. Default arguments

Default arguments are 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 values 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;
}


8. 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 with the main browsers, even the latest version of Node.js still isn’t. To solve this problem, you can use Babel which falls back 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 out our post about it.

Jscrambler

The leader in client-side Web security. With Jscrambler, JavaScript applications become self-defensive and capable of detecting and blocking client-side attacks like Magecart.

View All Articles