map: Transform Every Item

Grade 10, page 3 of 12. A one-minute read.

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:

JavaScript
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?

JavaScript
const doubled = [];
for (const n of numbers) {
  doubled.push(n * 2);
}

With map, it's one line:

JavaScript
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:

JavaScript
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:

JavaScript
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 ]
Watch outForgetting to return

If your callback uses curly braces, you must write return. Otherwise every item becomes undefined:

JavaScriptHas a bug
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.)

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning