Great ES6 features to enhance Node.js development

In this article, I’ll list down and explain some of the exciting ES6 features that I have been using in my Node.js development.

Here is a list of them.

  • Arrow Functions in ES6
  • Classes in ES6
  • Blocked scope with let and const
  • Template Literals in ES6
  • Multi line strings in ES6

Arrow Functions in ES6

Arrow functions in ES6 are a shorthand alternatives to function expression. You will usually use arrow functions in place of anonymous callback function expression.
One of the advantages of arrow functions is that it gives you a shorthand syntax compared to function expression as shown below.

Arrow Functions

setTimeout(function(){
//do something
}, 100);

//the above can be written as below with arrow functions.

setTimeout(() => {
//do something
}, 100);

 

The other advantage of using arrow functions is that they refer to lexical this (they do no bind to their own this). So you won’t have to do var self = this to refer to the context of lexical this. This can be demonstrated as follows.

Lexical this

function ciphyTest(){
    this.x = 1;
    setTimeout(function(){
        console.log(`Function Expression ${this.x}`); // this outputs 'Function Expression undefined'
    }, 1000);
    
    setTimeout(() => {
        console.log(`Arrow function ${this.x}`);  // this outputs 'Arrow function 1', takes value of this from surroundings
    }, 1000);
}

ciphyTest();

 

Classes in ES6

If you are an OOPs fan you would love this feature. With ES5 creating classes was not as straight forward as using the class keyword. Classes could have been created using functions of object literals and there was always a debate as to which ways are better than the other. ES6 brings the class keyword along with it. So we can simply define classes using the class keyword just like we would do in any other object oriented language.

However, classes in es6 under the hood use the old prototype model of ES5 and are a bit more than a syntactic sugar over it.
Here are a few thing you should know about ES6 classes.

  • An ES6 class can be declared using the class keyword.
  • A constructor can be defined using the constructor() method.
  • Static methods can be declared using the static keyword
  • Sub classes can be created using the extends keyword (Inhereitance)
  • The class without the extends keyword is called as the base/parent class
  • super keywords can be used to call base class methdods from the subclass

Let’s see them in action.

Classes in ES6

class Vehicle{
    constructor(name){ //definig constructor
        this.name = name;
    }
    
    wheels(){ //defining methods
        console.log(`${this.name} has wheels`);
    }
}

class Car extends Vehicle{ //sub-classes
    wheels(){
        super.wheels(); //call method from base class
        console.log(`${this.name} has 4 wheels`);
    }
}

var c = new Car('Lamborghini Veneno');
c.wheels();

 

Blocked scope with let and const

If you have been working with javascript in the past years, you know there is only one way to declare variables i.e using var. var is function scoped, but the let in ES6 is blocked scope. A block is anything between two curly braces.

let

function ciphyVar(){
    var x = 1;
    if(true){
        var x = 2; // same variable
        console.log(x); // 2
    }
    console.log(x); // 2
}



function ciphyLet(){
    let x = 1;
    if(true){ // this is a block
        let x = 2; // different variable
        console.log(x); // 2
    }
    console.log(x); // 1
}

 
Use of let leads to cleaner code and also should prevent defects in quality management systems, in regards to the reuse of same variables.

const, on the other hand, follows all the principles of the let but it creates a read-only value and prevents rebinding/ reassignment to the same variable. However the value of a const variable is not immutable.

const

const ciphyConst = 10;

ciphyConst = 20; // throws as error

ciphyConst++  // throws as error

if(true){
    const ciphyConst = 70; // this works as const operates in block scope
    console.log(ciphyConst); // gives 70
}

console.log(ciphyConst); // would still give 10

var ciphyConst = 10; //throws an error

// const also works on objects
const ciphyObject = {"key": "value"};

const ciphyObject = {"newKey": "newValue"}; //throws an error

//However keys are not protected.
ciphyObject.key = "myNewValue"; //works
//use Object.freeze() to make object mutable.

 

Template Literals in ES6

This is becoming one of my favorite feature of ES6.
We already know how annoying it is to display variables with string. In ES5 we had to use a combination of "string" + var + "string" to output variables inside strings.

With ES6 we don’t have to take that pain anymore. We can output expressions using ${..} inside back ticked ` strings.

Template Literals

ES5 : -
var name = "Rahil";
console.log("Welcome "+ name + "!");


ES6
var name = "Rahil";
console.log(`Welcome ${name}!`);

 

Multi line strings in ES6

One of the cool features of ES6 is Multi-line strings, in ES5 we would use concatenation to define long strings. But in ES5 we can simply define them using backticks.

Multi line strings

ES5:-

var long_string = "This is line one "
                += "and this is line two";

ES6:- 

var long_string = `This is line one
                 and this is line two`;

 

Conclusion

ES6 or ECMAscript 6 is mainstream now, at least for Node.js if not for browsers, and the sooner you adapt to the new features the better, not to mention it will only improve your development experience with Node.js or JavaScript for that matter. This was just a collection ES5 features I use for my node development and I’m sure there are more that I’ll learn with time.

Call to Action

As I said, these are only a few ES6 features I use, but we know there are more. It would be great if you could let me know what features of ES6 you love. And if you think there is one you can contribute to this article you can connect to me via Twitter or the contact us page, make sure you have the explanation and a code example of the same. I’ll add your response to the post along with your twitter handle(or any other, only one) mention.

More Info

  • Better Node with ES6 is an exhaustive and a great article on ES6 for Node.js.
  • A Book you might find helpful: ES6 and beyond.
Facebook
Twitter
LinkedIn
Pinterest

Related posts