Search code examples
javascriptpythonlist-comprehension

Something like list comprehension in JS?


For example, in Python we have such a convenient tool — instead of writing like

values = [1,2,3,4,5]
altered_values = []
for v in values:
    altered_values.append(v*25)

We could just write

altered_values = [v*25 for v in values]

Are such one-liners possible in Javascript?


Solution

  • Short answer: no.

    Long answer: kind of, under very special circumstances: Array comprehensions are a very similar tool, which might be present in the ECMAScript 7 edition of the language (that's the one after the next). With them you can write:

    var altered_values = [for (v of values) v*25];
    

    Currently they are only supported by the Spidermonkey engine, ie. Firefox.

    Edit: as JamesAllardice points out below, they are also available for use via the Babel transpiling library, which means you can practically use them in any browser.