Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are ES6 Array comprehensions no longer valid?

Tags:

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) } 
like image 237
screenm0nkey Avatar asked Nov 23 '15 13:11

screenm0nkey


People also ask

Is there array comprehension in JavaScript?

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.

What is after ES6?

ES5, ES6, ES7, ES8, ES9: What's new in each Version of JavaScript.

Does TypeScript have list comprehension?

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.


2 Answers

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); 
like image 87
nikc.org Avatar answered Oct 05 '22 04:10

nikc.org


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.
like image 22
Dave Barton Avatar answered Oct 05 '22 04:10

Dave Barton