Before You .map(), Read This!
1. What is a map()?
In a very crude definition, in JavaScript, the .map()
function goes through each item in a list (called an array). It makes some changes to each item and gives you a new list with those changed items.
2. Why is it required?
The purpose is very crisp and clear.
1. Purpose: When you want to perform changes on one or more items of the array.
2. Non-Destructive: It doesn't change the original array.
3. New Array: Always returns a new array containing the changed items.
3. When NOT to Use .map()
Changing Original Array: If you need to modify the original array,
.map()
is not the right choice because it creates a new array and leaves the original one unchanged.Unused Return Value: If you don't need a new array and are only interested in side-effects (like printing each element), then
.map()
is not the most efficient method to use.Conditional Insertion:
.map()
will always return a new array of the same length as the original array. If you need to conditionally include or exclude elements,.map()
is not the right choice.Performance Concerns: If performance is a critical aspect and the operation is computationally intensive, you may want to consider other options, like
for
loops, that can break out early or skip iterations.Flat-Mapping: If you need to flatten arrays as you transform elements, using
.map()
followed by.flat()
might not be as efficient as using.flatMap()
.No Array Return: If you don't need an array as a return type (perhaps you need an object or a string),
.map()
would not be appropriate.Chain of Transformations: If you are planning to use multiple array methods like
.filter()
and.reduce()
in addition to.map()
, you might want to consider methods like.reduce()
that can accomplish multiple tasks in a single loop to improve performance.
Using .map()
in the scenarios above is often seen as an anti-pattern—a solution that does more harm than good. So, knowing when not to use .map()
is as crucial as knowing when to use it.
4. Getting Started with .map()
: Syntax and Example
Syntax
Here's the basic syntax:
const newArray = originalArray.map(callbackFunction);
The callbackFunction
is a function that takes up to three arguments:
currentValue
: The current value being processed in the array.index
(optional): The index of the current value being processed in the array.array
(optional): The array thatmap()
was called upon.
Basic Example
Here's a simple example where we double each number in an array:
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(function(num) {
return num * 2;
});
console.log(doubled); // Output: [2, 4, 6, 8, 10]
console.log(numbers); // Output: [1, 2, 3, 4, 5] (unchanged)
5. The Three Musketeers of .map()
: Parameters Explained.map()
takes a callback function with three parameters: currentValue
, index
, and array
(the original array you're working with).
You might be scratching your head, wondering why you'd need that original array as a parameter when you're already calling .map()
on it.
Good question! Trust me, there are scenarios where this third parameter is invaluable. It's so important that I've dedicated an entire separate page just to explain when and why to use it.
Example 1: Using only the current value
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map((num) => {
return num * 2;
});
We start with an original list of numbers
[1, 2, 3, 4, 5]
In the
.map()
function, we pass a callback function that has a parameter namednum
. Thisnum
holds the value of each array item temporarily as.map()
goes through the array.We create a new list called
doubled
that will keep our doubled numbers. Here's how it fills up:After the first step:
doubled
gets its first number, which is2
(because1 x 2 = 2
).After the second step:
doubled
now has two numbers:[2, 4]
(because2 x 2 = 4
).And so on: We keep going like this until every number from the original list has been doubled and added to
doubled
.
In the end, doubled
will have [2, 4, 6, 8, 10]
.
Example 2: using two parameters - currentValue and index
When working with arrays, there are situations where you need to know not just the value of each item, but also its position in the array. This is where the index
parameter comes in handy. Let's explore this with a real-world example.
Real-World Scenario: Coloring Alternate Rows in a Table
Imagine you have a table and you want to color alternate rows for better readability. To determine whether a row should be blue or green, you can use the row's position or index in the list.
Here's some code that demonstrates this:
const rows = ['Row 1', 'Row 2', 'Row 3', 'Row 4', 'Row 5'];
const coloredRows = rows.map((row, index) => {
if (index % 2 === 0) {
return { text: row, color: 'blue' };
} else {
return { text: row, color: 'green' };
}
});
console.log(coloredRows);
What's Happening in the Code?
Original List: We start with an original list of row names—
['Row 1', 'Row 2', 'Row 3', 'Row 4', 'Row 5']
.The
.map()
Function with Two Parameters: We use.map()
and provide a function that accepts two arguments:row
(which represents each row's text) andindex
(which represents the position of the row in the list).Determine Even or Odd: We use the
index
parameter to check if a row is in an even or odd position. This is done with theindex % 2 === 0
check.Assigning Colors: Based on the even or odd index, we assign the color
blue
for even andgreen
for odd rows.Result: The
coloredRows
array is created, and each entry contains an object with the row text and its color. You can then use this data to render the table rows with their respective colors.
And there you have it! The index
parameter helps us perform actions based on the position of items in an array. It's a valuable tool for cases like this, where the sequence or order of elements matters.
Conclusion
We've covered a lot of ground today, exploring how the .map()
function in JavaScript allows you to transform arrays in a clean and efficient manner. We've dived into the roles of the currentValue
and index
parameters, along with practical examples to demonstrate their utility.
But wait, there's more! You might be wondering about the third parameter that .map()
accepts, which is the original array itself. It's a fascinating topic with its own set of practical use-cases. Stay tuned, as I'll be dedicating an entire post to this subject shortly.
I hope the information shared in this blog has been helpful and has clarified how and when to use the .map()
function. As always, happy coding!
Subscribe to my newsletter
Read articles from Shreyas Ananth directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by