Array Comprehensions

Champions: Dave Herman, Brendan Eich
Details: full proposal
ES wiki: here

Array comprehensions were introduced in JavaScript. Comprehensions are a well-understood and popular language feature of list comprehensions, found in languages such as Python and Haskell, among many other languages. The syntax was 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.


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) ]

See Also