Overview of ES6 Features in JavaScript

Overview of ES6 Features in JavaScript

JavaScript ECMAScript 6 (ES6) brings new syntax and new awesome features to make your code more modern and more readable. It allows you to write less code and do more. ES6 introduces us to many great features like arrow functions, template strings, class destruction, Modules… and more. Let’s take a look.

Basic ES6 Features are

  • The let & const keyword
  • Arrow Functions
  • The For/Of Loop
  • Classes
  • Promises
  • Template Literals
  • Default Parameters
  • Array and object destructing
  • Rest parameter and Spread operator
  • Import and export

The let & const keyword

The let keyword allows you to declare a variable with block scope.

var x = 10; // Here x is 10
{
    let x = 2; // Here x is 2
}
// Here x is 10

The const keyword allows you to declare a constant (a JavaScript variable with a constant value). Const variables must be assigned a value when they are declared:

Constants are similar to let variables, except that the value cannot be changed.

const PI = 3.141592653589793;
PI = 3.14;      // This will give an error
PI = PI + 10;   // This will also give an error

Arrow Functions

Arrow functions allows a short syntax for writing function expressions.

You don’t need the function keyword, the return keyword, and the curly brackets.

// ES5
var x = function(x, y) {
    return x * y;
}
// ES6
const x = (x, y) => x * y;
  • Arrow functions do not have their own this. They are not well suited for defining object methods.
  • Arrow functions are not hoisted. They must be defined before they are used.
  • Using const is safer than using var, because a function expression is always a constant value.
  • You can only omit the return keyword and the curly brackets if the function is a single statement. Because of this, it might be a good habit to always keep them:
const x = (x, y) => { return x * y };
OR
const x = (x, y) => x * y; // no need of return keyword in case of single statement

The For/Of Loop

The JavaScript for/of statement loops through the values of an iterable objects.

for/of lets you loop over data structures that are iterable such as Arrays, Strings, Maps, NodeLists, and more.

The for/of loop has the following syntax:

for (variable of iterable) {
    // code block to be executed
}

Example:
var cars = ["BMW", "Volvo", "Mini"];
for (var x of cars) {
  document.write(x + "<br >");
}

variable – For every iteration the value of the next property is assigned to the variable. Variable can be declared with const, let, or var.
iterable – An object that has iterable properties.

Classes

Classes are the core of object oriented programming (OOP). They make your code more secure and encapsulated. Using classes gives your code a nice structure and keeps it oriented.

JavaScript Classes are templates for JavaScript Objects.

class ClassName {
    constructor() { … }
}

To create a class, use the class keyword followed by the name of the class with two curly brackets.

class Car {
    constructor(name, year) {
        this.name = name;
        this.year = year;
    }
}

Promises

Promises are a new feature of ES6. It’s a method to write asynchronous code. It can be used when, for example, we want to fetch data from an API, or when we have a function that takes time to be executed. Promises make it easier to solve the problem, so let’s create our first Promise!

let myPromise = new Promise(function(resolve, reject) {
    resolve(); // when successful
    reject(); // when error
});
// Must wait for a fulfilled Promise.
myPromise.then(
    function(value) { // code if successful },
    function(error) { // code if some error }
);

If you log your console, it will return a Promise. So, if we want to execute a function after data is fetched, we will use a Promise. The Promise takes two parameters: resolve and reject to handle an expected error.

let myPromise = new Promise(function(resolve, reject) {
  setTimeout(function() { resolve("Hello World!!"); }, 3000);
});
myPromise.then(function(value) {
  console.log('Success', value);
}, function(error) {
  console.log('Error', error);
});

Template Literals

Template literals or template strings are pretty cool. We don’t have to use the plus (+) operator to concatenate strings, or when we want to use a variable inside a string.

The old syntax: ES5
function myFunct(name, age) {
    return 'Hi, My name is: '+ name + ' and i am '+ age + ' years old';
}
console.log(myFunct("TCM", 26));
Output: Hi, My name is: TCM and i am 26 years old

The New syntax: ES6
const myFunct = (name, age) => `Hi, My name is: ${name} and i am ${age} years old`;
console.log(myFunct("TCM", 26));
Output: Hi, My name is: TCM and i am 26 years old

So simple! It’s a really huge difference between the old syntax and ES6. When playing with strings, the literal string in ES6 looks more organized and well structured than ES5.

Default parameters

When I work in PHP, I usually use default parameters. These allow you to define a parameter in advance.

So, when you forget to write the parameter, it won’t return an undefined error because the parameter is already defined in the default. So when you run your function with a missed parameter, it will take the value of the default parameter and it will not return an error.

Look at this example:

const myFunct = (name, age) => Hi, My name is: ${name} and i am ${age} years old;
console.log(myFunct("TCM"));
Output: Hi, My name is: TCM and i am undefined years old

The function above returns undefined, because we forgot to give it the second parameter age.

But if we used the default parameter, it won’t return undefined, and it will use its value when we forget to assign a parameter.

Look at this example:

const myFunct = (name, age = 26) => Hi, My name is: ${name} and i am ${age} years old;
console.log(myFunct("TCM"));
Output: Hi, My name is: TCM and i am 26 years old

Array and Object Destructing

Destruction makes the assignment of the values of an array or object to the new variable easier.

The old syntax:

const user = {
  id: 12345,
  name: "TCM",
  age: 26
};

let id = user.id;
let name = user.name;
let age = user.age;
console.log(id, name, age);
Output: 12345 TCM 26

With ES6 syntax:

const user = {
  id: 12345,
  name: "TCM",
  age: 26
};

let { id, name, age } = user;
console.log(id, name, age);
Output: 12345 TCM 26

With ES5, we have to assign each value to each variable. With ES6, we just put our values within curly brackets to get any property of the object.

Note: if you assign a variable that is not identical to the name of property, it will return undefined. For example, if the name of the property is name and we assign it to a username variable, it will return undefined.

Rest Parameter and Spread Operator

The Rest Parameters syntax allows a function to accept an indefinite number of arguments as an array.

const sum = (…args) => args.reduce((total, num) => total + num, 0);
console.log(sum(1, 2, 3));
Output: 6

The Spread Operator has the same syntax as the rest parameter, but the spread operator takes the Array itself and not just the arguments. We can use the Spread parameter to get the values of an Array, instead of using a for loop or any other method.

const arr=['said', 20, 'Hi', 'How are you?'];

const Func = array => [...array, "hello world"];
console.log(Func(arr));
Output: ["said", 20, "Hi", "How are you?", "hello world"]

Import and Export

Using import and export in your JavaScript application makes it more powerful. They allow you to create separate and reusable components.

If you are familiar with any JavaScript MVC framework, you will see that they use import and export to handle the components most of the time. So how do they really work?

It is simple! export allows you to export a module to be used in another JavaScript component. We use import to import that module to use it in our component.

For example, we have two files. The first is named detailComponent.js and the second is named homeComponent.js.

In detailComponent.js we are going to export the detail function.

const myFunct = (name, age = 26) => Hi, My name is: ${name} and i am ${age} years old;
export default myFunct;

And if we want to use this function in homeComponent.js, we will just use import.

import myFunct from './detailComponent.js';
console.log(myFunct("TCM"));
Output: Hi, My name is: TCM and i am 26 years old

If we want to import more than one module, we just put them within curly brackets.

import {myFunct, user, profile} from './detailComponent.js';
console.log(myFunct("TCM"));
console.log(user);
console.log(profile);

So cool, isn’t it?! Feel free to leave a comment below.