Array Methods (map, filter, reduce, forEach)
Expert-Level Explanation
Array methods in JavaScript are functions that can be used to perform operations on arrays. These include map
, filter
, reduce
, and forEach
, each serving a different purpose.
Creative Explanation
Think of array methods as different kitchen tools used to prepare a meal:
map
is like a knife that modifies each ingredient (element).filter
is like a sieve, separating wanted ingredients from unwanted ones.reduce
is like a blender, combining all ingredients into one final product.forEach
is like tasting each ingredient separately while cooking.
Practical Explanation with Code
let numbers = [1, 2, 3, 4, 5];
let doubled = numbers.map(number => number * 2); // [2, 4, 6, 8, 10]
let evens = numbers.filter(number => number % 2 === 0); // [2, 4]
let sum = numbers.reduce((total, number) => total + number, 0); // 15
numbers.forEach(number => console.log(number)); // 1 2 3 4 5
Real-world Example
Array methods are like different staff members in a warehouse:
map
is like a worker who repackages items.filter
is quality control, removing defective items.reduce
is the accountant, summarising all items' values.forEach
is like inspecting each item on the conveyor belt.