JavaScriptDébutant 5 min·Updated: 2026-09-07
Mastering map(), filter(), and reduce() in JavaScript (Clear Examples)
Learn to process arrays declaratively and immutably without error-prone imperative loops.
Concepts & Theory
`map()` transforms each item in an array and returns a new array of identical length without mutating the input.
`filter()` tests each element against a predicate and returns an array containing matching items.
`reduce()` aggregates all elements into a single accumulator value (e.g. total sum, grouping dictionary).
Code Example
Run in PlaygroundJAVASCRIPTPROJET CARTHAGE
const produits = [
{ nom: "Clavier Mécanique", prix: 120, categorie: "Tech" },
{ nom: "Souris Ergonomique", prix: 80, categorie: "Tech" },
{ nom: "Cahier de Notes", prix: 15, categorie: "Papeterie" },
];
// 1. Filtrer les produits Tech
const tech = produits.filter((p) => p.categorie === "Tech");
// 2. Extraire les prix avec remise de 10%
const prixReduits = tech.map((p) => p.prix * 0.9);
// 3. Calculer le total du panier avec reduce
const totalPanier = tech.reduce((accumulateur, p) => accumulateur + p.prix, 0);
console.log("Total Tech :", totalPanier, "€"); // 200 €Common Pitfalls & Mistakes
✗ Omitting the initial accumulator value in reduce()
Incorrect / Error
const sum = [{cost: 10}].reduce((acc, i) => acc + i.cost);Idiomatic / Correct
const sum = [{cost: 10}].reduce((acc, i) => acc + i.cost, 0);Without an initial value, reduce defaults to the first object instead of zero, causing string or type bugs.
Frequently Asked Questions
Does map() mutate the original array?▾
No, `map()` is a pure array method that always returns a newly allocated array, leaving the original intact.
Practice in Carthage
Start JavaScript CourseMaster JavaScript with interactive exercises
Complete hands-on code challenges in your browser with real-time feedback and progressive hints.
