10 Ecmascript-6 Tricks You Can Perform Right Now

ES6 Hiway sign

By Dale Schouten

We live in a fluid world. I first started hearing about HTML5 several years ago now, and I’ve been using it for at least two, yet it won’t be officially ready until next year at the earliest. While HTML is making great strides, another leg of the stool is progressing nicely as well. New JavaScript* features are coming, outlined in the standard known as Ecmascript 6. Though it’s not finalized, it is approaching stability and implementation is coming along in various forms.

You’ve probably heard about some of the cool features on the way, like module support, classes and a bunch of syntactic niceties, but you might not have had a chance to try them. You can try out the traceur compiler which has support for many new features. It’s a wonderful tool, and you can use it to build a full webpage or app taking advanage of some of these features.

There are also quite a few new features already available in the browser. While several browsers have implemented some of the upcoming JS features, I’ve had particularly good luck with Firefox Aurora. Aurora is an experimental version of Firefox, esssentially a version number or two ahead of the standard release. It’s more stable than nightly, but not quite ready for primetime. Nevertheless, I’ve found it pretty reliable, in fact I’ve been using it as my primary browser for months without any problems, but your mileage may vary.

All that is to say that if you do want to try ES6, and you aren’t afraid of Firefox Aurora, here’s some new features you can test out.

1. Extract the weekday, month, date and year from Date() in one fell swoop:

var [day, month, date, year] = Date().split(' ');

Using destructured assignment, you can extract multiple fields from an array and assign them to a set of variables. It doesn’t quite work for objects yet, but arrays work fine.

2. Set default parameter values:

f = function(x, y=1) {console.log(x,y)};
f(22);
// 22 1

Finally, we can get rid of the various (sometimes dubious) default parameter patterns, with built-in support for default parameters. Once destructured object assignments are complete, we’ll be able to use those for setting defaults from named parameter objects as well.

3. Use variable args without the arguments object:

f = function(x,y,z, ...a) { console.log(a) }
f(1,2,3,7,8,9,'a','b','c');
// 7 8 9 'a' 'b' 'c'

One word of wisdom I often see is that the arguments object is not an array, and you should not treat it like one. With the rest operator, you don’t need the arguments object, and the rest of the parameters really do end up in a real array.

4. Define a function quicker than you can type “function () {}”:

f = (x) => x*x

For a language that is arguably functional at heart, JavaScript picked an unusually verbose keyword to describe functions, especially given the prevalence of callback routines and object methods which involve an awful lot of repetition of the word “function”. And while not everyone loves CoffeeScript, I suspect even the haters are sometimes jealous of its arrow notation as a shortcut to describe functions. The fat arrow knocks out two birds with one stone, as it also provides a lexical this pointer, the lack of which confuses many a new JavaScript programmer.

5. Create variables with block scope:

f = function () {
    let n=1;
    for (let n=5,i=0; i<n; i++) {
        console.log(i);
    }
    console.log(n);
};
f();
// 0 1 2 3 4 1

Perhaps the most anticipated feature of Ecmascript 6 is the arrival of Block Scoping. One of the single biggest drawbacks of JavaScript is its scoping, especially the lack of block scoping, leading to common anti-patterns like declaring every single local variable at the top of a function, regardless of where it’s used. With the new let statement we finally have variables with lifetimes that last only until the end of the block.

6. Make things constant:

f = function() {
    const two = 2;
    two = 5;
    console.log(two);
}
f();

In one of my first programming courses, I remember the teacher discussing the Fortran equivalent of a symbolic constant, but she said something like “I know it’s good for something but I’m not sure what”. These days the goodness of const is generally well understood, but the lack of it in one of the worlds most prevalent languages is not. No more; with ES6 it is finally here.

7. Intercept and rewrite attribute accesses:

var point = {x:1};
var w = {set: function(t,p,v) {
                console.log(p,v);
            }
        };
p = Proxy(point, w);
p.x = 2;
// prints 'x 2', but doesn't change p.x

While getters and setters are becoming more familiar to JavaScript programmers, Proxy provides extensive functionality to wrap an object so that a number of types of access may be monitored or modified. A more comprehensive list of “proxyable” items may be found here.

8. Create and manipulate Sets:8. Create and manipulate Sets:

s = new Set();
[2,3,5,4,5,2,2].map(x => s.add(x))
for (i of s) {console.log(i)}
// 2 3 4 5

There’s a reason that mathematicians invented sets, and sometimes developers need them too. Now instead of needing to implement them or rely on another JS library, they’re just there.

9. Use an object as a key value:

m = new Map();
o = {passwd: "my name is my password"};
m.set(o, "content")
console.log(m.get(o))
// "content"

Map may seem redundant at first, as it appears to be a more complicated version of an object, i.e. just a set of key: value pairs with less convenient syntax. But with objects, the key must be a string (dot notation is just shorthand for strings that work as JavaScript identifiers). With Maps, the key can be a JavaScript object, which can be really handy at times.

10. Iterate and Generate:

nums = function () {yield 1; yield 2; yield 3;}
for (i of nums()) {console.log(i)}
// 1 2 3

I must confess, while I think generators are great, when someone asks me for an example of when they are useful, I stumble a bit. You can always use a class with a next function and emulate the functionality of a generator, but generators can be cleaner and more concise. But even if you don’t find uses for generators yourself, you’ll want to use the “for of” loop. The “for of” construct provides the kind of functionality for iterating through an array that we always wished we had from the “for each…in” loop. Specifically, it only iterates through the iterable part of an Array, ignoring additional properties that may be part of it:

a = [1,2,3,4]
a.sparse = false
 
for (t of a) {
    console.log(t)
}
// 1 2 3 4

There are a few caveats to consider. While these examples should work fine in a Firefox (Aurora) console, they don’t all work in a script tag (or included .js file) unless you set  <code>type="application/javascript;<wbr />version=1.7"</code>. Further, not everything is finalized, and/or Firefox’s implementation may diverge from the unfinished standard in some areas, so take everything with a grain of salt. Finally, if you don’t want to use Aurora, you could try standard Firefox. since I started working on this article Firefox has almost caught up, such that with the current Release (24) I think everything on this list except Proxy is working. There are a few things that work in traceur but not in Firefox, so that’s worth exploring as well. In any case, consider it another way to prepare for the coming storm that is Ecmascript 6.

I mean “storm” in a good way, of course.

Для получения подробной информации о возможностях оптимизации компилятора обратитесь к нашему Уведомлению об оптимизации.
Возможность комментирования русскоязычного контента была отключена. Узнать подробнее.