ES 6

Ni­co­las Be­vac­qua walks through the first steps of learn­ing about and us­ing ES6, the lat­est set of stan­dard­ised JavaScript lan­guage fea­tures

net magazine - - CONTENTS -

Ni­co­las Be­vac­qua walks through the lat­est JavaScript lan­guage fea­tures

The sixth ECMAScript spec­i­fi­ca­tion was fi­nalised in June 2015, and there is now a flurry of JavaScript fea­tures com­ing our way. You can start us­ing th­ese fea­tures to­day, pro­vided you know the right tools for what you want to do. In this tu­to­rial I’ll be cov­er­ing the most ex­cit­ing new fea­tures, as well as a couple of dif­fer­ent ways you can start us­ing them in your projects right away.

Un­der­stand­ing the new lan­guage fea­tures, and how they can be used, will help you de­cide whether to adopt ES6 or stay in the ES5 camp. You may want to be on the bleed­ing edge and con­sider ES6 a crit­i­cal ad­di­tion to the pro­duc­tiv­ity of your team, but it comes at the cost of you and your team tak­ing the time to learn ES6.

To date, no browser has 100 per cent cov­er­age on ES6. The spec­i­fi­ca­tion is still fresh, and im­ple­men­ta­tions are un­der ac­tive de­vel­op­ment. Re­ly­ing solely on to­day’s JavaScript en­gines means you’ll find many ES6 fea­tures don’t work, are only par­tially im­ple­mented, or are com­pletely miss­ing.


The so­lu­tion to the patchy browser sup­port is to use a tran­spiler. Tran­spi­la­tion is just a fancy way of say­ing the com­pi­la­tion of sim­i­lar lan­guages. By us­ing a tran­spiler to trans­form ES6 code into ES5, browsers (which have great ES5 sup­port nowa­days) can in­ter­pret ES6 with­out com­plain­ing, since you feed them the com­piled ES5 code.

Tran­spilers pro­vide a con­sis­tent base­line for your ES6 pro­grams, but they aren’t per­fect. Prox­ies, for ex­am­ple, are very hard to rep­re­sent in ES5 code, and are un­avail­able to tran­spilers.

You can use the on­line Ba­bel REPL ( ba­ repl) to try out the ex­am­ples in this ar­ti­cle. You can write ES6 code on the left, and see the tran­spiled version change in real time on the right. It’s a treat when it comes to learn­ing ES6. For de­vel­op­ing en­tire ap­pli­ca­tions in ES6, your best bet is to pair the Ba­bel tran­spiler with web­pack or Browser­ify to han­dle mul­ti­ple in­ter­con­nected small mod­ules.

The lat­est version of the lan­guage in­cludes fea­tures such as ar­row func­tions, tem­plate lit­er­als, block scop­ing, col­lec­tions, na­tive prom­ises, and many more. I can’t pos­si­bly cover all of it in one go, but we’ll go over my favourites, and the most prac­ti­cal fea­tures.

Tem­plate Lit­er­als

In ES6 we get tem­plates that are sim­i­lar to those in Mus­tache, but na­tive to JavaScript. In their purest form, they are al­most in­dis­tin­guish­able from reg­u­lar JavaScript strings, ex­cept they use back­ticks ( ` ) as a de­lim­iter, in­stead of sin­gle or dou­ble quotes.

All the strings be­low are equiv­a­lent: "The quick brown fox jumps over the lazy dog" ' The quick brown fox jumps over the lazy dog' ` The quick brown fox jumps over the lazy dog`

Back­ticks aren’t con­ve­nient just be­cause they rarely ap­pear in text. Th­ese strings can be multi-line with­out any ex­tra work on your be­half. That means you no longer need to con­cate­nate strings us­ing + , or join them us­ing an ar­ray. var text = ` This is a multi- line

string.`; Tem­plate lit­er­als also let you add vari­ables into the mix by wrap­ping them in an in­ter­po­la­tion: var color = ' brown'; var tar­get = ' lazy dog'; ` The quick ${color} fox jumps over the ${tar­get}`; // <- ' The quick brown fox jumps over the lazy dog' You’re not lim­ited to vari­ables; you can in­ter­po­late any ex­pres­sion in your tem­plates. var in­put = -10; var mod­i­fier = 2;

ES6 in­cludes ar­row func­tions, tem­plate lit­er­als, block scop­ing, col­lec­tions, and more

` The re­sult of mul­ti­ply­ing ${ in­put} by ${mod­i­fier} is ${ in­put * mod­i­fier}`; // <- ' The re­sult of mul­ti­ply­ing -10 by 2 is -20' ` The ab­so­lute value for ${ in­put} is ${ Math. abs( in­put)}`; // <- ' The ab­so­lute value for -10 is 10'

Block scop­ing and let

Let’s move on to some other prac­ti­cal fea­tures. The let state­ment is one of the most well-known fea­tures in ES6. It works like a var state­ment, but has dif­fer­ent scop­ing rules. JavaScript has al­ways had com­pli­cated scop­ing rules, which drove many pro­gram­mers crazy when they were first try­ing to fig­ure them out.

Declarations us­ing var are func­tion-scoped. That means var declarations are ac­ces­si­ble from any­where in the func­tion they were de­clared in. On the other hand, let declarations are block.scoped . Block scop­ing is new to JS in ES6, but it’s fairly com­mon­place in lan­guages like Java or C#.

Let’s look at some dif­fer­ences be­tween the two. If you had to de­clare a vari­able us­ing var in a code branch for an if , your code would look like this: func­tion sortCo­or­di­nates ( x, y) { if ( y > x) { var temp = y; y= x; x = temp; } re­turn [x, y]; } That rep­re­sents a prob­lem be­cause the process known as hoist­ing means the dec­la­ra­tion for temp will be ‘pulled’ to the top of its scope. Ef­fec­tively, our code be­haves as if we’ve writ­ten the fol­low­ing snip­pet. For this rea­son, var is in­ef­fec­tive when

deal­ing with vari­ables that were meant to be scoped to code branches. func­tion sortCo­or­di­nates ( x, y) { var temp; if ( y > x) { temp = y; y= x; x = temp; } re­turn [x, y]; } The so­lu­tion to that prob­lem is to use let .A let dec­la­ra­tion is also hoisted to the top of its scope, but its scope is the im­me­di­ate block (de­noted by the near­est pair of brack­ets), mean­ing that hoist­ing won’t re­sult in un­ex­pected be­hav­iour or vari­ables get­ting mixed up.

Even though let declarations are still hoisted to the top of their scope, at­tempts to ac­cess them in any way be­fore the ac­tual let state­ment is reached will throw. This mech­a­nism is known as the ‘tem­po­ral dead zone’.

How­ever, rather than be­ing a prob­lem, this fea­ture will in fact of­ten help users catch er­rors in their code. At­tempts to ac­cess vari­ables be­fore they were de­clared usu­ally led to un­ex­pected be­hav­iour when us­ing var , so it’s a good thing that let pre­vents it en­tirely. con­sole. log( there); // <- run­time er­ror, tem­po­ral dead zone let there = 'dragons';

Const declarations In ad­di­tion to let declarations, we can also ob­serve const declarations be­ing added to the lan­guage. In con­trast with var and let , const declarations must be as­signed to upon dec­la­ra­tion. const pi = 3.141592653589793; const max; // <- Syn­taxEr­ror At­tempts to as­sign to a dif­fer­ent value to a const vari­able re­sult in syn­tax er­rors, as the com­piler can tell you’re try­ing to as­sign to a const vari­able. const max = 123; max = 456; // <- Syn­taxEr­ror Note that const only means the dec­la­ra­tion is a con­stant ref­er­ence – it doesn’t mean the ref­er­enced ob­ject be­comes im­mutable. If we as­sign an ob­ject to a const vari­able client , we won’t be able to change

client into a ref­er­ence to some­thing else, but we will be able to change prop­er­ties on client like we’re used to with other dec­la­ra­tion styles. const client = getHttpClient(' http://pony­foo. com'); client. maxCon­cur­rency = 3; // works be­cause we're not as­sign­ing to client

Ar­row funct ions Th­ese are prob­a­bly the best known fea­ture in ES6. In­stead of declar­ing a func­tion us­ing the func­tion key­word, you can use the _"ar­row"_ no­ta­tion, as seen be­low. Note how the re­turn is im­plicit, as well as the paren­the­sis around the x pa­ram­e­ter. [1, 2]. map( func­tion ( x) { re­turn x * 2 }); // ES5 [1, 2]. map( x=> x * 2); // ES6 Ar­row func­tions have a flex­i­ble syn­tax. If you have a sin­gle pa­ram­e­ter you can get away with drop­ping the paren­the­sis (al­though you can in­clude it if you want), but you’ll need it for meth­ods with zero, two, or more pa­ram­e­ters.

[1, 2]. map(( x,i) => x * 2 + i); // <- [2, 5]

The let state­ment is one

of the most well-known

fea­tures in ES6. It works

like a var state­ment,

but has dif­fer­ent

scop­ing rules

If your method does more than re­turn the re­sults of eval­u­at­ing an ex­pres­sion, you could wrap the right­hand part of the dec­la­ra­tion in a block, and use as many lines as you need. If that’s the case, you’ll need to add the re­turn key­word back again. x => { // mul­ti­ple state­ments re­turn re­sult } An im­por­tant as­pect of ar­row func­tions is that they are lex­i­cally scoped. That means you can kiss your var self = this state­ments good­bye.

The fol­low­ing ex­am­ple in­creases a counter and prints the cur­rent value, ev­ery sec­ond. With­out lex­i­cal scop­ing you’d have to .bind the method call, use .call , .ap­ply , or the self hack that I men­tioned ear­lier. func­tion count () { this. counter = 0; setIn­ter­val(() => con­sole. log(++this. counter), 1000); } count(); // <-1, .. 2, .. 3, ... Ar­row func­tions are rec­om­mended for short meth­ods, like those typ­i­cally pro­vided to .map and .fil­ter it­er­a­tors. Us­ing ar­row func­tions may take you a day or two to get used to, but you’ll quickly fall in love with the new syn­tax.

Note that you prob­a­bly shouldn’t use ar­row func­tions every­where. In­stead, con­sider them for each case. For ex­am­ple, an ar­row func­tion might be a good re­place­ment of anony­mous func­tions, but not so much for named func­tions.


Now you’ve learned about Ba­bel, tem­plate lit­er­als, block scop­ing, let , const and ar­row func­tions, you’re ready to give ES6 a shot for the first time. Head on to the Ba­bel REPL ( ba­ and start try­ing out code.

Com­pat­i­bil­ity prob­lems No browser fully sup­ports ES6 yet. Find an in-depth guide at­pat­i­ble-276

ES6 to­day If you want to start us­ing ES6 right now, you’ll need to use a JavaScript tran­spiler like Ba­bel

Method block scop­ing Func­tion declarations are block scoped in ES6, mean­ing they won’t be able to leak se­crets placed in block-scoped vari­able declarations

For ref­er­ence The ar­ti­cles on Pony Foo in the ES6 se­ries cover top­ics, rang­ing from get­ting started to mas­ter­ing prox­ies and gen­er­a­tors

Ar­row func­tions There are sev­eral ways to de­clare ar­row func­tions. It might take you a few tries to get them right, but you’ll love them!

Newspapers in English

Newspapers from Australia

© PressReader. All rights reserved.