Top ES6 feature one should know
So ES6, sounds a new cool name around the corner in tech distrct. If you are still not aware what ES6 is, its a new and improved JavaScript version over ES5. Here are some top feature that a Javascript developer should know.
1.) Promises 2.) Template Literals and Multi-line Strings 3.) Block-Scoped Constructs 4.) Enhanced Object Literals 5.) Arrow Functions 6.) Default Parameters 7.) Assignments 8.) Classes 9.) Modules
1.) Promises
In JS world, promise
s always been a controversial topic. There are lots of libraries out there implementing promise in there tastes. jquery’s deferred, q, bluebird, deferred.js to name just a few. Opinions conflict over using async, generators, callbacks etc. ECMA has officially implemented promises in ES6. That’s a good news for JS community over having a standard implementation of promises.
Let’s consider a trivial example in plain old ES5
var random = function (resolve, reject){
if (Math.random() * 10 <= 9) {
resolve('Yay!');
} else{
reject(new Error('I failed!'));
}
};
random(
function (resolveValue){ console.log(resolveValue) },
function (error){ console.log(error) }
);
This can be rewriten using promises in es6, as below
new Promise ((resolve, reject) => {
if (Math.random() * 10 <= 9) {
resolve('Yay!');
}
reject(new Error('I failed!'));
}).then (
(resolveValue) => { console.log(resolveValue) },
(error) => { console.log(error) }
)
So far, we’ve mostly same number of lines of code without any visible obvious benefit. But this would benefit in case there are lots of nested calls that could rather result is famous callback hell.
ES6 also has fail-and-catch-all
callback, that seems to be a good improvement over handling and catching them in every implementation.
We would dive deeper into ‘Promises in ES6’ in future posts. So keep tuned here.
2.) Template Literals/Interpolation and Multiline strings
In my honest opinion, template literals in JS were long overdue. It’s tough for a developer to use +
again and again to concat string for the sole purpose of string interpolation.
And believe me after few long interpolation it becomes messy to maintain and looks bad.
Here is how it was done in ES5 or what we are forced to use
var first_name = 'Pankaj',
last_name = 'Baagwan'
var full_name = function(){
console.log("We got your full name: It is " + first_name + ' ' + last_name);
};
But in ES6, it can be done easily and looks beautiful. This can be done using ${VAR_HERE} withing back-ticked string. Have a look
var full_name = ()=> {
console.log(`We got your full name: It is ${first_name} ${last_name}`)
};
Similarly, es6 gives ability to write multiline strings using backticks. Currently we have to use +
for concatenation and some other measures to have a multiline strings. Have a look
var lipsum = 'Mauris tempus velit at sapien euismod placerat.\n'
+ 'Donec commodo dui sit amet imperdiet tincidunt.\n'
+ 'Ut blandit, et tincidunt, nisl enim ornare lacus\n'
+ 'eget pellentesque ex libero eget lacus.\n'
+ 'Praesent luctus mauris, eu dictum elit ultricies eu.\n'
+ 'Etiam viverra consectetur bibendum at nec turpis.\n'
+ 'Cras at porttitor tellus, vitae dapibus justo.\n'
+ 'Nullam eget neque at elementum egestas eget et elit.\n'
+ 'Proin blandit euismod. Suspendisse malesuada erat.'
and in es6, it delightfully simple to curate multiline strings, whatever written within backticks
var lipsum = `Mauris tempus velit at sapien euismod placerat.
Donec commodo dui sit amet imperdiet tincidunt.
Ut blandit, et tincidunt, nisl enim ornare lacus
eget pellentesque ex libero eget lacus.
Praesent luctus mauris, eu dictum elit ultricies eu.
Etiam viverra consectetur bibendum at nec turpis.
Cras at porttitor tellus, vitae dapibus justo.
Nullam eget neque at elementum egestas eget et elit.
Proin blandit euismod. Suspendisse malesuada erat.`
3.) Block-Scoped Constructs
So first thing that caught my eye while going through es6 outline is script. My initial thought was, “Why do we need another var
?”. But after lots of digging I came to conclusion that its different and for good.
let
is new var
, which restricts visibility/scope of variable at block level instead of at immediate function level; that was the case with var
So, finally we can have some predictability on visibility, though in my opinion there is long way to go for javascript to evolve further.
function sayHello(){
if(true){
var hello = "Hello";
}
return hello;
};
console.log(sayHello());
The construct above should technically be errornous and hello
should not be visible outside if
block. But is ES5; we are living with this. ES5, by default have function level scope and any variable declared within function scope; moves to the top; hence hello
has visibility outside if
block within sayHello
function
To overcome, this ES6 has introduced let
, though var
stays with same visibility rules. So let
can be used to restrict visibility of variable in es6 as needed. Now replace var
with let
in sayHello
function. Let’s have a look
function sayHello(){
if(true){
let hello = "Hello";
}
return hello;
};
console.log(sayHello());
ES6 has another construct that is also block scoped and called const
; it’s an immutable as well. To demonstrate, here are a bunch of constants and they all are okay because they belong to different blocks:
function sayHello(){
const hello = "Hello ES6";
if(true){
const hello = "Hello World";
}
return hello;
};
console.log(sayHello());
When executed, it should print Hello ES6
since that’s what visible.
In my opinion, though let
and const
are welcome but letting var
stay will add to confusion and lot will need to be considered for choosing one over other.
Read more here