map
- Node.js course
- Beginner
- Lesson 59/116
- 5 min
Learn to transform each element with .map.
The map method
The map method transforms each element of an array and returns a new array with the results. The original array stays unchanged; you get a fresh array of transformed values.
The syntax is array.map(fn). Here fn is a function called for each element. The arrow function form p => p * 2 is enough for this lesson; you will see the details in the Functions group.
Example: [1, 2, 3].map(n => n * 2) returns [2, 4, 6].
Three parameters of map
The function map calls can take three parameters: (element, index, array). Most of the time only element is used; the rest are optional.
For example ['a', 'b', 'c'].map((letter, i) => i + letter) puts the position in front of each letter: ['0a', '1b', '2c']. This is handy when you need an item together with its position.
map always returns an array of the same length as the original. To skip or trim items you need filter; that is the next lesson.
Practice Add tax to prices
Define an array of prices [100, 200, 50]. Use map to create a new array where each price includes 18% tax (new price = old price + old price * 18 / 100), and print the result with console.log.
Starter code
const prices = [100, 200, 50];
// Create a new array with tax and print itSample solution
const prices = [100, 200, 50];
const withKdv = prices.map(p => p + p * 18 / 100);
console.log(withKdv);Expected output
[ 118, 236, 59 ]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does map return?
[1, 2, 3].map(n => n * 2)- 6
- [1, 2, 3]
- [2, 4, 6] Correct answer
- [3, 6, 9]
Explanation: each element doubles, so the new array is [2, 4, 6].
2 Double each value
const nums = [1, 2, 3];
const doubled = nums.map(n => ____);
const nums = [1, 2, 3];
const doubled = nums.map(n => n * 2);
Explanation: n => n * 2 doubles each element.
3 Match the map parts
| Term | Meaning |
|---|---|
array.map(fn) |
Transform call |
fn |
Function called per element |
element |
First parameter of fn |
new array |
What map returns |