Don’t Make This Mistake With the JavaScript Array Map() Method
The array is a widely used data structure in many programming languages. In this article I will discuss the map method and discuss examples on when not to use it.
Many other articles may be found on the internet that explain how and what this function does. Because I've seen many programmers employ the map method where it isn't needed, I decided to create this post from my perspective.
The map() method is used to create a new array from the original array by applying a function to each element of the original array.
Example
Before we get to anything let's find out briefly what this method does. Say we have an array of numbers where each element represents a radius of a circle. We want to create a new array containing the area of the circle. See the below snippet.
const radiusArray = [20, 40, 60];
console.info("Generating area array using just a for loop");
const areaArray = [];
for (let i = 0; i < radiusArray.length; i++) {
areaArray.push(Math.floor(Math.PI * radiusArray[i] * radiusArray[i]));
}
console.log(areaArray);
console.info("Generating area array using array.map()");
const areaArrayWithMap = radiusArray.map((radius) => {
return Math.floor(Math.PI * radius * radius);
});
console.log(areaArrayWithMap);
In the first block. we are using a for loop to iterate through all elements of the radiusArray. We have declared a new variable called areaArray to store our calculated areas. In the body of the loop, we calculate the area using the radius and push it to the areaArray.
If we run the above snippet we'll get the following output
// Generating area array using regular method
[1256,5026,11309]
// Generating area array using array.map()
[1256,5026,11309]
As you can see both our methods produce the same output but, using the map() method we reduced few lines of code. The map method can be further reduced to just one line.
const areaArrayWithMap = radiusArray.map((radius) => Math.floor(Math.PI * radius * radius));
Use map() when you want to modify an array to produce another array. I have seen a lot of beginners make the mistake of using the map method where it is not designed to be used. Don't use map() when:
- you don't intend in using the array that the method returns
- you don't return a value in the body of the callback function
If you intend on not using the returned array of the map method try using forEach or for...of instead.