const - JS | lectureWorking With Arrays

The map Method

Working With Arrays

Let's start seeing the three data transformation methods in practice, starting with the map method in this lecture. As we just learned, the map method is yet another way that we can use to loop over arrays. But unlike forEach, the map method will give us a brand new array, which will contain the result of applying a callback function to the original array elements in each position. So let's see how that works.

Let's consider the below movements array:

script.js
const movements = [300, 600, -800, 7000, -750, -150, 90, 1500];

Let's suppose that, the values in the movements array are in euros, and we want to convert them to US dollars. And let's suppose 1 euro is equal to 1.1 US dollars. So now what we want to do is to basically multiply each element of the movements array by 1.1.

script.js
const movementsUSD = movements.map((movement) => movement * 1.1);

// OR

const movementsUSD = movements.map(function (movement) {
  /**
   * Returning the value that we want the new array to have in the current position.
  */
  return movement * 1.1;
});

console.log (movements);
console.log(movementsUSD);

MAP METHOD

Never mind the multiplication errors. I'll explain to you a little bit later where they come from, but essentially you can notice, for example, that we have the value 330 in our new array, which is the result of 300 * 1.1. And so, indeed, we ended up with a new array containing all the movements converted from euros to US dollars.

And again, that's because that is exactly what we returned from our callback function. We could, of course, have returned simply something else. Like for example the number 23.

script.js
const movementsUSD = movements.map((movement) => 23);

console.log(movementsUSD); // [23, 23, 23, 23, 23, 23, 23, 23]

We now have an array of the same length in each position containing 23 because that's what we returned from the callback function. Hence, in each iteration of the original movements array, it simply puts 23 into the new array at the same position.

I guess you've also noticed the original array wasn't mutated. As we've learned in the previous lecture, the map method returns a new array with the new elements. And that's really the fundamentals of how the map method works.

Next let's see how we could do the same operation using the for-of loop.

script.js
const movementsUSD = [];
for (const movement of movements) {
  movementsUSD.push(movement * 1.1);
}

console.log(movementsUSD); // [330, 630, ...]

The output will exactly be the same. But what I want to point out here is that it's a completely different philosophy. When using the map method, we use a function to solve the problem of creating a new array. While on the other hand, when using the for-of loop, we loop over one array and then manually create a new one.

Before we move on, note that the map method is more in line with functional programming which is something that I have mentionned a couple of times in this course and we will talk about it later in greater detail. There is definitely a push going on in the direction of functional programming. i.e., over a more functional language. Hence in modern JavaScript, using methods together with callback functions is the new modern way of doing stuff.

Next, let's now experiment and explore a little bit more the map method. Just like the forEach method, the map method also has access to the same three parameters. So besides the current array element (movement parameter in our callback function), we also get access to the current index and the whole array.

script.js
const movementsDescriptions = movements.map((movement, index, movements) => {
  if (movement > 0) {
    return `${index + 1} Deposit of ${movement}`;
  } else {
    return `${index + 1} Withdrawal of ${Math.abs(movement)}`;
  }
});

console.log(movementsDescriptions);

MAP THREE PARAMS

We can actually simplify the whole if-else statement above to one line since the only thing that changes is the movement type (deposit or withdrawal).

script.js
const movementsDescriptions = movements.map((movement, index, movements) => {
  return `${index + 1} ${movement > 0 ? 'Deposit' : 'Withdrawal'} of ${Math.abs(
    movement
  )}`;
});

console.log(movementsDescriptions);

You can actually get rid of the last parameter in our callback function (movements) since we are only using the first two, i.e., the current element and the current index. And with this, I hope that by now it is really clear how all this works.

Now you could say that what we did above with the map method is essentially the same as what we did with the forEach method. But in fact, there is a big, big difference between these two approaches.

So before, we printed each line individually to the console as we looped over the array. In each iteration, we performed some action that was visible in the console, and we can call this a side effect. So the forEach method creates side effects.

But now, with the map method, all we did was to return each of the strings from the callback. Each of these strings then gets added to a new array. And after the iteration was over, we logged the entire array to the console. We didn't log the elements one by one. Hence in the above map method, we did not create a side effect in each iteration. All we did was build a brand new array, and this idea of side effects will become important again as we talk more about functional programming.