André Selmanagić

about programming, games and tools

Coolest Javascript Features - Part 1: let, logical operators, destructuring, labels

This is going to be an unsorted list about the nicest Javascript features. Look closely at the title: Javascript! Thus this list may contain features only present in the Mozilla-implementation and not standardized in ECMAScript! I am going to update this list every now and then.

Block scoping with let

Support: ECMAScript Harmony, Javascript 1.7, Mozilla-only (as of September 2010)

Finally lexical scoping / block scoping in Javascript. Declare variables with let instead of var. May come in handy when you are creating closures in a loop.

Logical operators && and ||

Support: should work in all modern browsers

Logical operators are nothing spectecular in programming languages. But Javascript handles them a little different. && and || don’t necessarily return boolean values, but can also return other types (objects, etc). Here are some examples from Angus Croll’s JavaScript blog:

1
2
3
4
5
//invoke callback if there is one
callback && callback();

//delay by argument or 20
delayBy(delay || 20);

But you should be careful, when using this with values that evaluate to false. See the following example:

1
2
3
//delay by argument or 20
var delay = 0;
delayBy(delay || 20);

0 will evaluate to false and thus delayBy will be called with 20.

|| is often used for setting default-values for functions parameters (well, harmony may contain that natively), but as shown that may not always lead to the expected behaviour, thus I wouldn’t recommend setting default values that way.

Destructuring

Support: ECMAScript Harmony, Javascript 1.7, Mozilla-only (as of September 2010)

Don’t confuse this with destructors known from languages like Java or C++. Destructuring assignment makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals

This allows things like swapping variables without a temporary variable, multiple return values and more. Here is an example for multiple return values from MDN:

1
2
3
4
5
6
7
function f() {
    return [1, 2];
}

var a, b;
[a, b] = f();
document.write ("A is " + a + " B is " + b + "\n");

The function simply returns an array, but the destructuring syntax allows to split this into multiple variables.

Labeling statements

Support: should work in all modern browsers

By labeling statements you can give them an identifier that you can refer to from somewhere else. That may come in handy when using loops with continue or break.

1
2
3
4
5
6
7
8
9
10
loopX:
for(var x = 0; x < 5; ++x)
{
    for(var y = 0; y < 5; ++y)
    {
        // ... do something
        if(...)
            break loopX;
    }
}

Comments