JS es6 (also known as es2015) is a set of new features to JS language aim to make it more intuitive when using OOP or while facing modern development tasks.
Check out the new es6 features at http://es6-features.org - it may clarify to you if you really intend to use it on your next NodeJS app
Check the compatibility level of your node version at http://node.green
If all is ok - let's code on!
Here is a very short sample of a simple hello world
app with JS es6
'use strict'
class Program
{
constructor()
{
this.message = 'hello es6 :)';
}
print()
{
setTimeout(() =>
{
console.log(this.message);
this.print();
}, Math.random() * 1000);
}
}
new Program().print();
You can run this program and observe how it print the same message over and over again.
Now.. let break it down line by line:
'use strict'
This line is actually required if you intend to use js es6. strict
mode, intentionally, has different semantics from normal code (please read more about it on MDN - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode)
class Program
Unbelievable - a class
keyword! Just for a quick reference - before es6 the only way do define a class in js was with the... function
keyword!
function MyClass() // class definition
{
}
var myClassObject = new MyClass(); // generating a new object with a type of MyClass
When using OOP, a class is a very fundamental ability which assist the developer to represent a specific part of a system (breaking down code is crucial when the code is getting larger.. for instance: when writing server-side code)
constructor()
{
this.message = 'hello es6 :)';
}
You got to admit - this is pretty intuitive! This is the c'tor of my class - this unique "function" will occur every time an object is created from this particular class (in our program - only once)
print()
{
setTimeout(() => // this is an 'arrow' function
{
console.log(this.message);
this.print(); // here we call the 'print' method from the class template itself (a recursion in this particular case)
}, Math.random() * 1000);
}
Because print is defined in the class scope - it is actually a method - which can be invoked from either the object of the class or from within the class itself!
So.. till now we defined our class.. time to use it:
new Program().print();
Which is truly equals to:
var prog = new Program(); // define a new object of type 'Program'
prog.print(); // use the program to print itself
In conclusion: JS es6 can simplify your code - make it more intuitive and easy to understand (comparing with the previous version of JS).. you may try to re-write an existing code of yours and see the difference for yourself
ENJOY :)