Functions and ScopeLesson 2.5
Higher-order functions: map, filter, reduce explained
higher-order functions, first-class functions, Array.map, Array.filter, Array.reduce, callback functions, method chaining, functional programming basics
Functions as First-Class Values
In JavaScript, functions can be passed as arguments and returned as values. Functions that operate on other functions are called higher-order functions. The three most important array higher-order functions are map, filter, and reduce.
map — Transform Every Element
const prices = [10, 25, 8, 42];
const withTax = prices.map(p => p * 1.2);
// [12, 30, 9.6, 50.4]
filter — Keep Matching Elements
const scores = [55, 82, 67, 91, 45];
const passing = scores.filter(s => s >= 60);
// [82, 67, 91]
reduce — Accumulate Into a Single Value
const cart = [
{ item: "Book", price: 12 },
{ item: "Pen", price: 3 },
{ item: "Bag", price: 30 },
];
const total = cart.reduce((acc, item) => acc + item.price, 0);
// 45
Chaining
const result = [1, 2, 3, 4, 5, 6]
.filter(n => n % 2 === 0) // [2, 4, 6]
.map(n => n * n) // [4, 16, 36]
.reduce((a, b) => a + b, 0); // 56
Each method returns a new array without mutating the original — a core principle of functional-style JavaScript.
