Babel used to support syntax for comprehensions but no longer does. None of the modern browsers support comprehensions anymore either. Also, as of 2017, it doesn't look like there are plans to re-add support anytime in the near future. With ES6, however, you could use generator functions to sort of simulate the functionality of a python-like list comprehension:
Consider this example:
const someArray = [1,2,3,4,5,6];
const evens = [...(function*() { for(let x of someArray) if(x%2 == 0) yield x;})()]
console.log(evens);
// [2,4,6]
This would work in browsers that support the current standard of ES6. There is a proposal right now for arrow generators that would make this syntax a little shorter.
I definitely wouldn't use this in production code unless you (and all those who are working on the code) are very comfortable with using generators as iterators. Also its kind of ugly. It does give you an advantage over map
, however. If you implemented this same thing using map
, then you would also need to remember to compact
afterwards. This is because map will return undefined for all the uneven numbers.
That would look like:
const someArray = [1,2,3,4,5,6];
const evens = someArray.map(x => {
if(x % 2 === 0) return x;
});
Of course filter
would work better in this example.
You can find the docs on generator functions here.