ECMAScript 6’s parameter destructuring and forEach()

[2013-02-28] esnext, dev, javascript
(Ad, please don’t block)
This blog post gives a brief introduction to destructuring in ECMAScript 6 and how the array method forEach() profits from it.

Destructuring

ECMAScript 6 allows you to destructure: the target of an assigment can be a pattern that allows you to look into the source of the assignment and assign to variables what you find there. The following is an example of destructuring used in a variable declaration:
    > let { first: f, last: l } = { first: 'Jane', last: 'Doe' };
    > f
    'Jane'
    > l
    'Doe'
Another example: you can swap the values of two variables x and y like this:
    [x,y] = [y,x];
Destructuring also works for parameters. The following function has two kinds of parameters: the first parameter is positional (identified by position), the remaining parameters are named (identified by name) and wrapped in a so-called options object (which is actually a second positional parameter).
    function foo(positional, { named1, named2 }) {
        return [ positional, named1, named2 ];
    }
Ways of calling the above function:
    > foo(123, { named1: 'abc', named2: 'def' })
    [ 123, 'abc', 'def' ]
    > foo(123, { named2: 'def', named1: 'abc' })
    [ 123, 'abc', 'def' ]
You can specify default values for both positional and named parameters, thus making them optional [1].

Destructuring and forEach()

Destructuring parameters in ES6 is useful for the Array.prototype.forEach() method. An example:
    let items = [ ['foo', 3], ['bar', 9] ];
    items.forEach(([word, count]) => console.log(word+' '+count));
Above, the argument of forEach() is an arrow function, a compact way of writing a function expression that is new in ECMAScript 6 [2]. The elements of an array can also be objects:
    let items = [ {word:'foo', count:3}, {word:'bar', count:9} ];
    items.forEach(({word, count}) => console.log(word+' '+count));
The object literal
    { word, count }
is an abbreviation for
    { word: word, count: count }
You could therefore write the above loop like this:
    items.forEach(({word: w, count: c}) => console.log(w+' '+c));
Note: ECMAScript 6 has new for-of loops where you can also use destructuring [3]:
    for ([word, count] of items) {
        console.log(word+' '+count);
    }

References

  1. Keyword parameters in JavaScript and ECMAScript.next
  2. ECMAScript.next: arrow functions and method definitions
  3. ECMAScript.next: for-of, iterators, generators