JavaScript arrays have dozens of methods, but you’ll use about six of them 90% of the time. These are the ones that matter for web development and React.Every method here takes a callback function — an arrow function that runs once for each item in the array.
If you need a new array, use .map(). If you need to do something with each item (log, send, update DOM), use .forEach(). The rule: .map() transforms, .forEach() performs actions.
.reduce() is powerful but can be hard to read. If a .map() + .filter() combination does the job, prefer that over .reduce(). Readability matters more than cleverness.
// ❌ Wrong: Curly braces but no returnconst doubled = [1, 2, 3].map(n => { n * 2; // Computes but doesn't return});console.log(doubled); // [undefined, undefined, undefined]// ✅ Correct: Add return with curly bracesconst doubled = [1, 2, 3].map(n => { return n * 2;});// ✅ Or use implicit return (no curly braces)const doubled = [1, 2, 3].map(n => n * 2);
This is the same arrow function gotcha from earlier. With curly braces, you need return. Without curly braces, the return is implicit. This mistake causes arrays of undefined.
Using .map() when you need .forEach()
Copy
// ❌ Wrong: Using map for side effects (the returned array is wasted)users.map(user => { console.log(user.name);});// ✅ Correct: Use forEach for side effectsusers.forEach(user => { console.log(user.name);});
.map() creates and returns a new array. If you don’t need that array, use .forEach() instead. Using .map() for side effects is wasteful and signals to other developers that you intended to transform data.
Mutating the original array by mistake
Copy
// ❌ Wrong: .sort() mutates the original arrayconst scores = [85, 92, 78, 95];const sorted = scores.sort((a, b) => a - b);console.log(scores); // [78, 85, 92, 95] — original is modified!// ✅ Correct: Copy first, then sortconst sorted = [...scores].sort((a, b) => a - b);console.log(scores); // [85, 92, 78, 95] — original unchanged
.sort(), .reverse(), .splice(), .push(), and .pop() all mutate the original array. If you need the original intact, spread it into a new array first: [...arr].sort().
Arrays handle lists. Now let’s learn about objects — JavaScript’s key-value data structure for representing entities like users, products, and API responses.