Mascara: Next Generation JavaScript compiler

Try it Download Buy About Documentation Blog Contact

Array Comprehensions

Array Comprehensions are a very cool syntax for transformations of arrays.

Syntax definition [Help]
[ expression [ for-clause ]* [ if-clause ] ]
The for-clause is defined like this:
Syntax definition [Help]
for [ each ] ( variable in array )

Example

[x*2 for each (x in [1,2,3])]
evaluates to the array [2,4,6]

When more than one for-clause is used, the expression is evalueated for every combination. Example

[x+y for each (x in [1,2,3]) 
     for each (y in [10,20,30])]
evaluates to [11,21,31,12,22,32,13,23,33]

The if-clause can be used to filter the results. Only the values where the if clause is satisfied, is passed through.

[x+y for each (x in [1,2,3]) 
     for each (y in [10,20,30])
     if (x*10==y)]
evaluates to [11,22,33]

for each means we iterate through the values of the input array.

for (wihout each) means we iterate through the properties of the object. This is somewhat less useful, but is convenient for e.g. debugging.

X Try!
Mascara JavaScript Generated JavaScript

Translating...
Show compiler settings