22
votes

The ES6 code snippet below is invalid. It used to be valid. I can still run it in old versions of Traceur but the latest Babel and Traceur don't seem to like the for-loop in an array anymore. Can anyone tell me why it's no longer valid.

let people = [
    {
        "firstName": "Belinda",
        "phone": "1-607-194-5530",
        "email": "[email protected]"
    },
    {
        "firstName": "Elizabeth",
        "phone": "1-155-446-1624",
        "email": "[email protected]"
    }
]

let phones = [for({phone} of people) phone];
console.log(phones)

The snippet below is valid ES6 so I know the destructing inside a for-loop is OK

for(let {phone} of people) {
  console.log(phone)
}
3
That's an array comprehension, it's an experimental proposal that never landed in ES6 / ES2015 - Paolo Moretti

3 Answers

37
votes

Array comprehensions were removed in BabelJS version 6. The ES2015 Specification has no mention of comprehensions, so they were probably dropped. A quick search through the ES Discuss mailing list archives came up empty on anything definitive.

As a slightly more verbose alternative there is Object.entries (a stage-3 feature in ES7) and Array.prototype.map.

let emails = people.map(({ email }) => email);
10
votes

http://exploringjs.com/es6/ch_faq.html#_does-es6-have-array-comprehensions is helpful:

Originally, ES6 was to have Array and Generator comprehensions (similarly to Haskell and Python). But they were postponed until after ES6, because TC39 wanted to explore two avenues:

  • It may be possible to create comprehensions that work for arbitrary datatypes (think Microsoft’s LINQ).
  • It may also be possible that methods for iterators are a better way to achieve what comprehensions do.
7
votes

Can anyone tell me why it's no longer valid.

Array comprehension didn't make it into the final version of ES6 and it doesn't seem to be considered for the next version either: https://github.com/tc39/ecma262