map creates a new array by running your callback on every item and collecting whatever it returns. The new array is always the same length as the original:
const prices = [10, 25, 40];
const withTax = prices.map((price) => price * 1.15);
console.log(prices);
console.log(withTax);
It prints
[ 10, 25, 40 ] [ 11.5, 28.749999999999996, 46 ]
(Hello again, floating point! See Grade 2.) Notice that the original prices array is untouched. map always gives you a brand-new array.
Remember the "build a new array" recipe from Grade 7?
const doubled = [];
for (const n of numbers) {
doubled.push(n * 2);
}
With map, it's one line:
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map((n) => n * 2);
console.log(doubled);
It prints
[ 2, 4, 6, 8, 10 ]
map works for any kind of transformation:
const names = ["mia", "omar", "zoe"];
console.log(names.map((name) => name.toUpperCase()));
console.log(names.map((name) => name.length));
console.log(names.map((name, i) => `${i + 1}: ${name}`));
It prints
[ 'MIA', 'OMAR', 'ZOE' ] [ 3, 4, 3 ] [ '1: mia', '2: omar', '3: zoe' ]
It's especially handy for pulling one property out of an array of objects:
const students = [
{ name: "Mia", score: 88 },
{ name: "Omar", score: 72 },
{ name: "Zoe", score: 95 },
];
const names = students.map((student) => student.name);
const scores = students.map((student) => student.score);
console.log(names);
console.log(scores);
It prints
[ 'Mia', 'Omar', 'Zoe' ] [ 88, 72, 95 ]
If your callback uses curly braces, you must write return. Otherwise every item becomes undefined:
const numbers = [1, 2, 3];
const doubled = numbers.map((n) => {
n * 2;
});
console.log(doubled);
It prints
[ undefined, undefined, undefined ]
Either drop the braces, (n) => n * 2, or add the return. (This is the same arrow-function bug from Grade 6, and it's even more common with map.)