4 Node ES6 Features Available Today

ES6 is here and the recent versions of Node (> 4.0) have integrated some new features. There’s no need for using a transpiler since it’s built into the language now, horray! These features don’t require a rewrite of code, just keep these in mind when starting the next Node app. Here’s a breakdown of a few Node ES6 features that are available today.

Const and Let

I’ll expand on this in another post, but when using Node 6 or above, always use const  or let . There’s no need for var anymore.

const allows defining a variable whose value cannot change after declaration. It’s also block scoped unlike var which is function scoped. This makes understanding where variable values are coming from easier.

let  is also block scoped but allows changing a variable’s value. Always use one of these two just to avoid the common bugs that happen when using var .

Arrow Functions

Aside from const/let, arrow functions will be one of the most used new features. Here’s a comparison on how a normal function compares to an arrow function.

For simple functions like this, it may seem trivial. The real power is in handling asynchronous callbacks, or functional operations on an array. The scope of this doesn’t change inside the function. For callbacks, this is a god send because developers can avoid the var self = this;  paradigm.

I have an article on arrow functions and some gotchas to look out for, so check that out for more information.

Default Values for Function Arguments

This has been a part of most static languages, but it’s now coming to JavaScript. This cuts down on superfluous code that checks values up front. No more accounting for undefined values inside the function.

With this new feature, a function can create required parameters. Setting the value evaluates upon calling the function. Also, parameters can be set to the result of a function. Put that together and the parameter can call a function if it’s left undefined. Inside that function, throw an error to let the developer know they left something out.

Class Declarations

Class are more sugar than functionality, but it’s a welcome addition. There are some key points to keep in mind though. Methods have a different syntax, and there’s no easy way to define private methods. There are ways around that though if that’s needed.

Using the same Users class from above, here’s how to define a class:

Having a keyword to define classes is a big change for JavaScript. It makes declaring them easier, and makes inheritance simple with the extends keyword. This was a tough thing to do in ES5. Now it’s as simple as defining a class is:

More is Coming

With each new version of Node, ES6 is becoming more native. The browsers need to start following suit soon. It’s nice being able to take advantage of these things without having to run a transpiler.