High-Order Functions (HOFs): map, filter, reduce
High-Order Functions are functions that take other functions as arguments or return them. They are powerful tools for working with arrays in JavaScript.
Key concepts
map
Creates a new array by applying a function to each element of the original array.
Exampleconst numbers = [1, 2, 3];
const doubled = numbers.map((num) => num * 2);
console.log(doubled); // [2, 4, 6]filter
Creates a new array containing elements that satisfy a given condition.
Exampleconst numbers = [1, 2, 3, 4, 5];
const evens = numbers.filter((num) => num % 2 === 0);
console.log(evens); // [2, 4]reduce
Reduces an array to a single value by repeatedly applying a function to elements.
Exampleconst numbers = [1, 2, 3, 4];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // 10Examples
map Example:
const numbers = [1, 2, 3];
const doubled = numbers.map((num) => num * 2);
console.log(doubled); // [2, 4, 6]filter Example:
const numbers = [1, 2, 3, 4, 5];
const evens = numbers.filter((num) => num % 2 === 0);
console.log(evens); // [2, 4]reduce Example:
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // 10Stuck on this one? Talk to Sumit.
Keys: F focus mode · ← → previous / next topic · Esc leave focus