The .map() Method
March 20, 2023
2 minute read
In comes the .map() method - .map() is an immutable method that creates a new array with the results of calling a function on every element in the original array. Think of it like copying and pasting an existing array as a brand new one with a modified version of each element.
Let's take a look at an example to understand the .map() method in action. Consider the following array of numbers
const numbers = [1, 2, 3, 4, 5];
Now, let's say we want to create a new array where each element is 2X the value of the corresponding element in the original array. Using the .map() method we can do it like so
const doubledNumbers = numbers.map(num => num * 2); console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]
In this example, we use an arrow function as an argument on the .map() method. The function takes one argument (num), which represents the current element being processed, and returns a new value (num * 2). The .map() method then returns a new array with the new values.