JavaScript ES6: Cool Features You Need to Know

JavaScript ES6

Why you should care about ES6?

JavaScript ES6 came out in 2015 already. However, most developers still used ES5 syntax because of compatibility issue with older browsers at that time, even though developers can also transpile JavaScript ES6 code into ES5.

Given that more and more users are relying on modern browsers and many front-end frameworks such as React and Vue.js are adopting ES6 syntax, you should start writing ES6 code too.

Cool features to check out

JavaScript ES6 introduces many new features; however, I won’t be covering all of them in this article. I therefore picked several features that you should really have a look at.

1. `let` and `const`

In ES5, you use `var` keyword to declare a variable. However, it can cause some unexpected issues.

Take a look at the following example:


```javascript
var i;
i = 34;
for (var i = 0; i < 4; i++) {
  console.log(i);
}
console.log(i);
```

For the last `console.log(i)`, you would expect the console to return 34. However, it returns 4 because of scoping.

To handle the scoping issue, ES6 introduced two new keywords for declaring variables: `let` and `const`.

Now take a look at the following example again:


```javascript
var i;
i = 34;
for (let i = 0; i < 4; i++) {
  console.log(i);
}
console.log(i);
```

The last `console.log(i)` will return 34 because `let` is scoped to the nearest code block.

For `const`, once a value is assigned to a constant, it becomes immutable.

For example:


```javascript
const number = 1;
number = 100; // Uncaught TypeError: Assignment to constant variable.
```

However, for an object, it's a bit different.


```javascript
const dog = {
  name: 'Milo',
  age: 3
};
dog.age = 5; // Returns 5 if we console.log(dog.age)
dog = { name: 'Sally' }; // Uncaught TypeError: Assignment to constant variable.
```

The values of object properties are mutable, but constant objects are immutable.

2. Arrow function

One of the syntactic treats introduced by JavaScript ES6 is the arrow function.

The arrow function keeps your code shorter.


```javascript
let numbers = [1, 2, 3, 4, 5];

// ES5 syntax
var sum = 0;
numbers.forEach(function (number) {
  sum += number;    
});
console.log(sum);

// ES6 syntax
let sum = 0;
numbers.forEach(number => { // parentheses can be omitted if only one parameter is passed to the function
  sum += number;
});
```

Another benefit is no binding of `this`. The context of `this` won't be lost inside the arrow function.

3. Default Parameter Values

In ES6, you can assign default parameter values for a function.


```javascript
// ES6 syntax
function add(x = 10, y = 20) {
  return x + y;
}
add();

// ES5 syntax
function add(x, y) {
  if (x === undefined) {
    x = 10;
  }
  if (y === undefined) {
    y = 20;
  }
  return x + y;
}
add();
```

4. String interpolation

In ES6, you can do string interpolation, just like you would do in other programming languages such as PHP.


```javascript
// ES6 syntax
let customer = { name: 'Calvin', amount: '$500' };
let message = `${customer.name} just spent ${customer.amount} on a product.`;

// ES5 syntax
var customer = { name: 'Calvin', amount: '$500' };
var message = customer.name + ' just spent ' + customer.amount + ' on a product.' 
```

5. Destructuring

If you look at the previous example, you can see I have to repeat `customer` several times. Imagine that we have something longer, like `customer.address.street`. We would have to write that long variable over and over again if we need that value stored in that variable. What a nightmare! So, let's take the example and do some refactoring in ES6.


```javascript
let customer = { name: 'Calvin', amount: '$500' };
let { name, amount } = customer;
let message = `${name} just spent ${amount} on a product.`;
```

6. Classes

In ES5, JavaScript doesn't support "classes", it just simulates this functionality through "prototypes". The syntax is very confusing and hard to read. With ES6, "classes" have been introduced, which makes writing object-oriented code more readable and organized.


```javascript
// ES6 syntax
class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  speak() {
    console.log(`Hi, I'm ${this.name} and I'm ${this.age} years old`);
  }
}

// ES5 syntax
function Person(name, age) {
  this.name = name;
  this.age = age;
}
Person.prototype.speak = function() {
  console.log('Hi, I\'m ' + this.name + ' and I\'m ' + this.age + ' years old');
}
```

7. New Built-In Methods

With ES6, it's much easier to find an element in an array.

For example, let say we've fetched a JSON response from an API server JSONPlaceholder.


```json
[
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
  },
  {
    "userId": 1,
    "id": 3,
    "title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
    "body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
  },
  {
    "userId": 1,
    "id": 4,
    "title": "eum et est occaecati",
    "body": "ullam et saepe reiciendis voluptatem adipisci\nsit amet autem assumenda provident rerum culpa\nquis hic commodi nesciunt rem tenetur doloremque ipsam iure\nquis sunt voluptatem rerum illo velit"
  },
  {
    "userId": 1,
    "id": 5,
    "title": "nesciunt quas odio",
    "body": "repudiandae veniam quaerat sunt sed\nalias aut fugiat sit autem sed est\nvoluptatem omnis possimus esse voluptatibus quis\nest aut tenetur dolor neque"
  }
]
```

We need to display the post with `"id": 5`. In this case, the `find` function may come in handy.


```javascript
// First we parse JSON into JavaScript object
let posts = [
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
  },
  {
    "userId": 1,
    "id": 3,
    "title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
    "body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
  },
  {
    "userId": 1,
    "id": 4,
    "title": "eum et est occaecati",
    "body": "ullam et saepe reiciendis voluptatem adipisci\nsit amet autem assumenda provident rerum culpa\nquis hic commodi nesciunt rem tenetur doloremque ipsam iure\nquis sunt voluptatem rerum illo velit"
  },
  {
    "userId": 1,
    "id": 5,
    "title": "nesciunt quas odio",
    "body": "repudiandae veniam quaerat sunt sed\nalias aut fugiat sit autem sed est\nvoluptatem omnis possimus esse voluptatibus quis\nest aut tenetur dolor neque"
  }
];

// We find the post with id 5
let targetPost = posts.find(post => post.id === 5);

// We display the post on console
console.log(targetPost);
```

Conclusion

There are many cool new features introduced in ES6. This would be a lengthy article if I were to cover all the features. If you want to know more about ES6, visit ECMAScript 6: New Features: Overview & Comparison.

For more by the same author, read Discovering TypeScript.

Leave a Reply

Your email address will not be published. Required fields are marked *

7 + thirteen =