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:

  • mapis like a knife that modifies each ingredient (element).

  • filteris like a sieve, separating wanted ingredients from unwanted ones.

  • reduceis like a blender, combining all ingredients into one final product.

  • forEachis 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:

  • mapis like a worker who repackages items.

  • filteris quality control, removing defective items.

  • reduceis the accountant, summarising all items' values.

  • forEachis like inspecting each item on the conveyor belt.