DEV Community

Discussion on: The JavaScript Array Map() Method

Collapse
 
sandordargo profile image
Sandor Dargo

Thanks for your article, the explanation is very clear.

On the other hand, I don't find the second example easy to grasp.

In modern programming, one of the most important principles is that elements should have names easy to understand and at the same time they should never lie about what their underlying structure does.

Let's have a look at it again:

const numbers = [4, 9, 36, 49];

let oddSquareRoots = numbers.map((num) => {
       if(num % 2 != 0) {
           return Math.sqrt(num)     
       }
       return num;
    })
Enter fullscreen mode Exit fullscreen mode

The map function returns a new list called oddSquareRoots. So what do I expect to have in it? It's very simple! Odd square roots! What do I get instead?

[4, 3, 36, 7]
Enter fullscreen mode Exit fullscreen mode

Those are not odd square roots! Those are some of the original numbers mixed with the square roots of some. Odd square roots apparently. Then I have a deeper look, I can figure out that actually, we have those original numbers that are even and the square roots of those that are odd. But that's not what the name says and that's something quite dangerous.

I don't work with JS a lot, so maybe there are different habits. Based on my experience, the example/use-case of applying a callback only on certain elements of a list is maybe a bit misleading.

Just like Python, JS also started to provide functional programming elements. Some of the main elements are map,filter and reduce. Each has its own very clear goal. I don't want to go into the very details, but in fact, they have very simple to understand names.

let oddSquareRoots = numbers.map((num) => {
       if(num % 2 != 0) {
           return Math.sqrt(num)     
       }
       return num;
    })
Enter fullscreen mode Exit fullscreen mode

In this case, map lies. What it does is filtering and then mapping some values and simply keeping some other values. Too many things in a map by an unnamed function.

If you want to get odd square roots, it's probably more readable to do it in two clear steps:

let oddSquareRoots = numbers.filter(num => num % 2 != 0).map(num => Math.sqrt(num));
let evenSquares = numbers.filter(num => num % 2 == 0);
console.log(oddSquareRoots.concat(evenSquares);
Enter fullscreen mode Exit fullscreen mode

If you need those numbers in their original order, maybe map is the only option, but the output's name still lies.

What do you think?

Collapse
 
sarah_chima profile image
Sarah Chima

Thank you, Sandor, for pointing this out. That example was just to show that logic can be used in the map method. However, as you clearly pointed out, the filter method is a more efficient way of achieving that. In fact, my next post is on the filter method. I am going to update that example to add this point in order not to confuse anyone.