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) }
The array comprehension syntax is a JavaScript expression which allows you to quickly assemble a new array based on an existing one. Comprehensions exist in many programming languages and the upcoming ECMAScript 7 standard defines array comprehensions for JavaScript.
ES5, ES6, ES7, ES8, ES9: What's new in each Version of JavaScript.
List Comprehension for TypeScript. This library implements comprehension for arrays, sets and maps for TypeScript. It also offer a powerful library to construct populated arrays that can be used with the comprehension functions.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With