Why map and not a loop?
Why modern code processes lists with methods, which methods do change the array, and when a loop is better.
for loop, and everyone was happy!" He's not wrong — a loop can do anything. But let's see why everyone around writes map.const prices = [100, 250, 50];
const withTaxLoop = [];
for (let i = 0; i < prices.length; i++) {
withTaxLoop.push(prices[i] * 1.2);
}
const withTaxMap = prices.map((p) => p * 1.2);
console.log(withTaxLoop);
console.log(withTaxMap);1. A method names the intent. Seeing filter, a reader knows at once "something is being selected here", before reading the condition. A loop has to be read in full to see what it does.
2. Fewer places for mistakes. A loop has a counter, a < or <= condition, an empty result array, a push. map has none of that — so there's nowhere to slip.
3. The original array doesn't change. map and filter return a new array. That matters when data is shared — say, in a React app's state.
4. Chains. filter(…).map(…).slice(0, 10) reads like a list of steps.
const menu = ["tuna", "sprat", "salmon"]; // the chef's order
function showSorted(list) {
return list.sort();
}
console.log(showSorted(menu));
console.log(menu); // the chef's menu got re-sorted too!
const safe = ["tuna", "sprat", "salmon"];
console.log([...safe].sort());
console.log(safe);[...list] saves the day.Another common question: is forEach worse than map? No — they do different jobs. map collects a new array from what the function returned. forEach collects nothing and returns undefined: it's for actions — print, send, save. Need the result but reached for forEach? You'll get undefined.
const prices = [100, 200];
const a = prices.map((p) => p * 2);
const b = prices.forEach((p) => p * 2);
console.log(a);
console.log(b);map. Just need to do something with each item — forEach.const fish = [5, 1, 4, 8];
let firstHeavy;
for (const w of fish) {
if (w > 3) {
firstHeavy = w;
break;
}
}
console.log(firstHeavy);
console.log(fish.find((w) => w > 3));find — a method too, and it stops by itself.map. We made peace on this: what matters is that the code reads well. And that the fish is fresh.Myth or fact?
Decide whether the statement is true. Got it wrong? Try again; once you're right, Byte explains what's going on.