JavaScriptEasy
What is the map() method?
map() creates a new array by calling a function on every element of the original array and collecting the return values; the original array is not changed and the new array always has the same length.
Signature
array.map((element, index, array) => newValue, thisArg?)
When to use it
Whenever you want to transform each item into something else: format prices, pick fields from objects, convert API data into view models, or render a list of React elements.
Rules that trip people up
- Always return a value. With curly braces you need an explicit
return; forgetting it gives an array ofundefined. - Do not use
mapfor side effects only. If you are not using the result, useforEachorfor...of. Linters flag unusedmapresults. - Returning an object literal from an arrow needs parentheses:
items.map(i => ({ id: i.id })). mapwithparseIntis a classic trap:["1", "2", "3"].map(parseInt)gives[1, NaN, NaN]becausemappasses the index asparseInt's radix. Usemap(Number)or an explicit arrow.- Async callbacks return promises, so
map(async ...)gives an array of promises. Wrap it inPromise.all.
Related
flatMap maps and flattens one level, useful when each item produces zero or many results. Array.from(iterable, mapFn) maps while converting.
Code example
js
1const products = [2 { id: 1, name: "Laptop", price: 1200 },3 { id: 2, name: "Mouse", price: 25 },4];56const labels = products.map((p) => `${p.name}: $${p.price}`);7console.log(labels); // ["Laptop: $1200", "Mouse: $25"]89const withTax = products.map((p) => ({ ...p, price: +(p.price * 1.2).toFixed(2) }));10console.log(withTax[1].price, products[1].price); // 30 25 - original untouched1112console.log(["1", "2", "3"].map(parseInt)); // [1, NaN, NaN] - index used as radix13console.log(["1", "2", "3"].map(Number)); // [1, 2, 3]1415// flatMap: each item can become 0..n items16const tags = [{ tags: ["js", "ts"] }, { tags: [] }, { tags: ["css"] }];17console.log(tags.flatMap((t) => t.tags)); // ["js", "ts", "css"]1819// Async map needs Promise.all20const fetchPrice = async (id) => id * 10;21const prices = await Promise.all(products.map((p) => fetchPrice(p.id)));22console.log(prices); // [10, 20]
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.