Table of Contents

This proposal has progressed to the Draft ECMAScript 6 Specification, which is available for review here: specification_drafts. Any new issues relating to them should be filed as bugs at http://bugs.ecmascript.org. The content on this page is for historic record only and may no longer reflect the current state of the feature described within.

Overview

Array comprehensions were introduced in JavaScript 1.7. Comprehensions are a well-understood and popular language feature of list comprehensions, found in languages such as Python and Haskell, inspired by the mathematical notation of set comprehensions.

Array comprehensions are a convenient, declarative form for creating computed arrays with a literal syntax that reads naturally.

Per iterators, default property value (not key) enumeration and custom value iteration may be done using for-of loop head syntax, rather than for-in.

Examples

Filtering an array:

[ x for (x of a) if (x.color === ‘blue’) ]

Mapping an array:

[ square(x) for (x of [1,2,3,4,5]) ]

Cartesian product:

[ [i,j] for (i of rows) for (j of columns) ]

Template String Nesting Example

The nesting example on the template string page

rows = [['Unicorns', 'Sunbeams', 'Puppies'], ['<3', '<3', '<3']],
safehtml`<table>${
  rows.map(function(row) {
    return safehtml`<tr>${
      row.map(function(cell) {
        return safehtml`<td>${cell}</td>`
      })
    }</tr>`
  })
}</table>`

Can be made prettier using other features of ES6. Using arrow functions:

rows = [['Unicorns', 'Sunbeams', 'Puppies'], ['<3', '<3', '<3']],
safehtml`<table>${
  rows.map(row => safehtml`<tr>${
    row.map(cell => safehtml`<td>${cell}</td>`)
  }</tr>`
}</table>`

or using comprehensions:

rows = [['Unicorns', 'Sunbeams', 'Puppies'], ['<3', '<3', '<3']],
safehtml`<table>${
  [safehtml`<tr>${
    [safehtml`<td>${cell}</td>` for cell of row]
  }</tr>` for row of rows]
}</table>`

or using hypothetical left-to-right array comprehensions with parenful syntax:

rows = [['Unicorns', 'Sunbeams', 'Puppies'], ['<3', '<3', '<3']],
safehtml`<table>${
  [for (row of rows) safehtml`<tr>${
    [for (cell of row) safehtml`<td>${cell}</td>`]
  }</tr>`]
}</table>`

Syntax

ArrayLiteral ::= ...
              |  "[" Expression ("for" "(" LHSExpression "of" Expression ")")+ ("if" "(" Expression ")")? "]"

Translation

An array comprehension:

[ Expression0 for ( LHSExpression1 of Expression1 ) ... for ( LHSExpressionn ) if ( Expression )opt ]

can be defined by expansion to the expression:

let (result = []) {
    for (let LHSExpression1 of Expression1 ) {
        ...
        for (let LHSExpressionn of Expressionn ) {
            if ( Expression )opt
                ArrayPush(result, Expression0);
            }
        }
    }
=> result
}

 
harmony/array_comprehensions.txt · Last modified: 2013/07/11 23:58 by rwaldron
 
Recent changes RSS feed Creative Commons License Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki