Jorge Valle

Jorge Valle

Jorge Valle is a front end developer with a particular passion for, and expertise in, JavaScript and user interfaces. Lately, he's also been diving into machine learning.

JavaScript's Array map() method

Whenever you encounter an array, and need to process each item iteratively, it's easy to default to using a loop. There's good reason for this: loops are a cornerstone of control flow.

Let's say, for example, that we want to return the square of an array of numbers.

With loops

Here we're looping through the values, and returning a fresh new array for the primes. I'm also assigning the squaredPrimes variable to an IIFE so that it returns immediately. Pretty standard stuff.

However, JavaScript offers a shorter and more idiomatic way of processing every element in an array without mutating the original: the array map() method.

Using arrow functions

Arrow function syntax, coupled with the map method, makes for a strikingly terse way to process an array.

Remember, the return statements in arrow functions is implicit, so we can omit it entirely.

Using normal functions

The return statement must be specified in normal functions.


Books, patrons and coffee in Caffè San Marco, Trieste