This content originally appeared on DEV Community and was authored by Aman kumar
When working with arrays, you donβt just want to loop through them β sometimes you want to transform them. Thatβs where .map()
becomes your best friend.
Today, we’ll explore how .map()
works and take it further with method chaining β a pattern that makes your code both powerful and readable.
What is .map()
?
.map()
is a method in JavaScript that creates a new array by applying a function to every element in the original array.
Letβs take an example:
const myNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const plusTen = myNumbers.map((num) => num + 10);
console.log(plusTen);
Output:
[11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
The original array stays unchanged.
.map()
returns a new transformed array.
With Explicit return
(Block Syntax)
const plusTen = myNumbers.map((num) => {
return num + 10;
});
You can use curly braces and
return
when your logic needs more space, but for simple expressions, inline (arrow) form is shorter and cleaner.
Method Chaining: map()
+ map()
+ filter()
Here’s where things get exciting. You can chain multiple array methods together to build transformations in one go.
const myNums = myNumbers
.map((num) => num * 10) // Step 1: Multiply each number by 10
.map((num) => num + 1) // Step 2: Add 1 to each result
.filter((num) => num >= 40); // Step 3: Keep only values >= 40
console.log(myNums);
Output:
[41, 51, 61, 71, 81, 91]
Letβs break it down:
-
1 * 10 = 10 β 10 + 1 = 11
βrejected (less than 40)
-
4 * 10 = 40 β 40 + 1 = 41
βkept
- …
-
9 * 10 = 90 β 90 + 1 = 91
βkept
Chaining makes your code more declarative, readable, and efficient. Itβs like passing your array through a pipeline of transformations.
When to Use .map()
Use Case | Why .map() Works |
---|---|
Adding tax to prices | Transforming each price individually |
Formatting dates | Changing each date format in an array |
Extracting properties | Like mapping over users to get their names |
Building UIs from data (React) | Transforming data into components |
Final Takeaway
- Use
.map()
when you want to transform each item in an array. - Combine
.map()
,.filter()
, and others for powerful, clean operations. - Prefer method chaining for concise and readable code.
This content originally appeared on DEV Community and was authored by Aman kumar