Array comprehension syntax

Olav Kjær olav at olav.dk
Sun Sep 13 11:56:16 PDT 2009


While experimenting with code-completion for ECMAScript I noticed a
limitation with array comprehension syntax.
The syntax as proposed (and implemented in Mozilla) has the output
expression before the loop and filter:

    [i.toString() for each (i in [1,2,3]) if (i != 2)]

The problem is that the variable i in the output expression is defined
by code to the right of it. Since people usually writes code left to
right, an editor with autocompletion is not able to provide type hints
like member proposals for i. This also limits what hints an editor can
give when writing an array literal. E.g. it cannot immediately flag an
undefined variable in the first expression in an array literal as a
possible typo, because we may be in the process of writing a
comprehension in which case the variable may be defined in the loop
which have not yet been typed. (Generally expressions in ECMAScript
never rely on definitions to the right of the expression -
comprehensions are the exception as far as I can tell.)

Traditional synax like:

   var x = [];
   for each (i in [1,2,3]) if (i != 2) x.push(i.toString());

or

   [1,2,3].filter(function(i) { return i != 2}).map(function(i){
return i.toString(); })

does not have the problem, since they read from left to right.

I wonder if it would make sense to turn array comprehension syntax
around so that they are written:

   [for each (i in [1,2,3]) if (i!=2) i.toString()]

This also makes it look more familiar since it is closer to the
traditional for-statement syntax. I realize this goes against the
tradition from most other languages which support list comprehensions.
e.g. Python.
I admit l like how it reads with the output expression first, but I
also think good tooling-support is pretty important for the success of
a language.

Regards
Olav Junker Kjær
(http://www.mascaraengine.com/)


More information about the es-discuss mailing list