Skip to content

JavaScript list comprehension

  • by

JavaScript does not have built-in support for list comprehension like some other programming languages do. However, you can achieve similar functionality using array methods and functional programming techniques.

JavaScript list comprehension example

Simple example code.

const numbers = [1, 2, 3, 4, 5];

// Squaring numbers using map()
const squares = => num * num);

// Filtering even numbers using filter()
const evens = numbers.filter(num => num % 2 === 0);

// Combining map() and filter() for more complex operations
const combined = numbers
  .map(num => num * num)
  .filter(square => square % 2 === 0);


JavaScript list comprehension

Does JavaScript support array/list comprehensions like Python?

Answer: JavaScript does not have built-in support for array/list comprehensions like Python. However, JavaScript introduced a new feature called “Array.prototype.flatMap()” starting with ECMAScript 2019 (ES10), which can be used to achieve a similar result.

const numbers = [1, 2, 3, 4, 5];

// Using Array.prototype.flatMap() for a similar effect
const squares = numbers.flatMap(num => [num * num]);

Output: [1, 4, 9, 16, 25]

Update: Array comprehensions were removed from the standard. Quoting MDN:

The array comprehensions syntax is non-standard and removed starting with Firefox 58. For future-facing usages, consider using, Array.prototype.filter, arrow functions, and spread syntax.

See this answer for an example with

let emails ={ email }) => email);

Comment if you have any doubts or suggestions on this JS List topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *