ECMAScript.next will have two kinds of comprehensions: array comprehensions and generator comprehensions. They allow one to quickly assemble an array or a sequence of elements. Comprehensions exist in many programming languages, for example: CoffeeScript, Python, Haskell, Clojure.
[for (x of a) for (y of b) if (x > y) [x,y]]This is equivalent to calling the following function (which uses ECMAScript.next’s for-of loop [1]).
function arrayComprehension() { let result = []; for (let x of a) { for (let y of b) { if (x > y) { result.push([x,y]); } } } return result; }There can be two kinds of clauses inside an array comprehension, in any order (but the first clause must be a for):
let numbers = [1,2,3]; let squares = [for (x of numbers) x*x];However, Array.prototype.map becomes more convenient in ECMAScript.next, too, because there will be arrow functions [2]:
let squares = numbers.map(x => x * x);
(for (x of a) for (y of b) if (x > y) [x,y])This is equivalent to calling the following generator function.
function* generatorComprehension() { for (x of a) { for (y of b) { if (x > y) { yield [x,y]; } } } }You can iterate over the yielded elements like this:
let compr = ( ... ); for (elem of compr) { console.log(elem); }
Note that while Haskell and Python use the right-to-left syntax, F# and C# both have left-to-right syntax.The advantage of left-to-right syntax is that it mirrors how one would write imperative loops and if statements (in the manner shown above).