Transforming with map
Learn to transform each element and create a new array with map.
Transforming with map
The map method runs a callback on every element and returns a brand new array. The original array stays untouched; instead you get a fresh array of the same length holding each transformed value.
Say you want to double every price in a list. map is the right tool. The callback can take three arguments: item, index and array. Most of the time only the item is used.
map never touches the original array
map is a pure function: it never writes back to the array you call it on. You receive the transformed values as a new array, and the old one stays as it was.
That is why calling map without assigning its result is useless. You must hand the result to a variable or to another call. When you want to keep the original intact, this behaviour is exactly what you need.
Exercise Convert prices to taxed prices
Multiply every price in prices by 18% tax and store the new array as withTax. Print the result.
Show example solution
const prices = [100, 250, 75];
// convert prices with tax (18%)
const withTax = prices.map(price => price * 1.18);
console.log(withTax);
Exercise Shout names in uppercase
Turn every name in names into uppercase and store the new array as shouted. Print the result.
Show example solution
const names = ["ayse", "mehmet"];
// convert names to uppercase
const shouted = names.map(name => name.toUpperCase());
console.log(shouted);
Test yourself
-
What is squares after const squares = [1,2,3].map(n => n*n);?
const squares = [1, 2, 3].map(n => n * n);- [1, 4, 9]
- undefined
- [1, 2, 3]
- 3
Show answer
[1, 4, 9] — Correct. map passes each element through the callback and returns [1, 4, 9].
-
produce each price with 18% tax
const prices = [100, 250]; const withTax = prices.map(price => ____); console.log(withTax);Show answer
const prices = [100, 250]; const withTax = prices.map(price => price * 1.18); console.log(withTax);