In this section, we will learn what the Array map() method is and how to use it in JavaScript.
JavaScript Arrays map() Method
Sometimes we have an array and want to add or remove content to each element of that array and create a new array as a result.
This is where the `map()` method can be used. As the name of the method suggests, the map() method is used for mapping! Basically, the `map()` method is used to map each element of the target array to another value (or even remove part of each element) and create a new array as a result.
Note: the method won’t change the elements of the old array.
Array map() Syntax:
array.map(function(currentValue, index, arr), thisValue)
Array map() Method Parameters:
This function takes 3 arguments:
- The first argument is the element in the array.
- The second argument is the index of that element.
- The third argument is a reference to the target array.
Other than the function, the `map()` method takes a second argument as well. This second argument, which is optional, is a reference to an object that will bind to the `this` keyword in the target function that we passed as the first argument.
Array map() Method Return Value:
The return value of the `map()` method is a new array with elements that are the results of calling the reference function on each element of the old array.
Example: using Array map() method in JavaScript
const arr = ["Amazon","Apple","Tesla"]; function eve(value, index ,arr){ return value + " Co."; } const newArray = arr.map(eve); console.log(`The new array: ${newArray}`); console.log(`The old array: ${arr}`);
Output:
The new array: Amazon Co.,Apple Co.,Tesla Co. The old array: Amazon,Apple,Tesla