1/1/1970
A higher-order method in JavaScript is a function that either:
map() – Transforms each item → Returns a new arrayforEach() – Executes a function for each item → Returns undefinedfilter() – Filters items by a condition → Returns a new arrayreduce() – Reduces array to a single value → Returns a single valuefind() – Finds the first matching item → Returns the first matchfindIndex() – Finds the index of the first match → Returns the indexsome() – Checks if any item meets a condition → Returns true or falseevery() – Checks if all items meet a condition → Returns true or falsesort() – Sorts array in place → Returns the sorted array (mutates original)flatMap() – Maps and flattens in one step → Returns a new flattened arrayHigher-order methods are commonly used in functional programming and allow for operations like mapping, filtering, and reducing collections.
higher-order function -> a function that Takes another function as an argument (callback) and Returns a function (optional).
map, filter, reduce)map: Takes a callback function and applies it to each element of the array.
const numbers = [1, 2, 3];
const squares = numbers.map(num => num * num); // [1, 4, 9]filter: Takes a callback function and returns elements that satisfy the condition.
const numbers = [1, 2, 3, 4];
const evens = numbers.filter(num => num % 2 === 0); // [2, 4]reduce: Takes a callback function and an accumulator to reduce the array to a single value.
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, num) => acc + num, 0); // 10You can define your own higher-order function:
function withLogging(func) {
return function (...args) {
console.log('Calling function with arguments:', args);
return func(...args);
};
}
const multiply = (a, b) => a * b;
const loggedMultiply = withLogging(multiply);
console.log(loggedMultiply(2, 3)); // Logs arguments and returns 6