Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
A higher-order function is a function that accepts other functions as arguments or returns a function. They treat functions as data!
Take other functions as parameters (callbacks)
Example: map, filter, forEach
Create and return new functions
Example: function factories
Array methods like map, filter, and reduce are higher-order functions!
const numbers = [1, 2, 3, 4, 5];
// map is a higher-order function
// It accepts a function as an argument
const doubled = numbers.map(function(num) {
return num * 2;
});
console.log(doubled);
// Output: [2, 4, 6, 8, 10]
// filter also accepts a function
const evens = numbers.filter(function(num) {
return num % 2 === 0;
});
console.log(evens);
// Output: [2, 4]Build a function that accepts another function
Build your own filter-like higher-order function
A function that returns another function is like a factory - it creates customized functions!
function makeMultiplier(factor) {
// Return a new function
return function(number) {
return number * factor;
};
}
// Create specialized functions
const double = makeMultiplier(2);
const triple = makeMultiplier(3);
const quadruple = makeMultiplier(4);
console.log(double(5)); // 10
console.log(triple(5)); // 15
console.log(quadruple(5)); // 20
// Each function remembers its 'factor'!Create customized greeting functions
Some higher-order functions both accept a function AND return a new function!
function withLogging(fn) {
// Accept a function, return a new function
return function(...args) {
console.log('Calling with:', args);
const result = fn(...args);
console.log('Result:', result);
return result;
};
}
// Original function
function add(a, b) {
return a + b;
}
// Wrap it with logging
const addWithLogging = withLogging(add);
addWithLogging(3, 5);
// Output:
// Calling with: [3, 5]
// Result: 8Create a function wrapper that limits how often a function can be called
const numbers = [5, 2, 8, 1, 9];
// sort accepts a function!
numbers.sort(function(a, b) {
return a - b;
});
console.log(numbers);
// [1, 2, 5, 8, 9]const nums = [1, 2, 3, 4, 5];
const sum = nums.reduce(
function(total, num) {
return total + num;
},
0
);
console.log(sum); // 15function compose(f, g) {
return function(x) {
return f(g(x));
};
}
const add2 = x => x + 2;
const mult3 = x => x * 3;
const add2ThenMult3 = compose(mult3, add2);
console.log(add2ThenMult3(5)); // 21function memoize(fn) {
const cache = {};
return function(arg) {
if (cache[arg]) {
return cache[arg];
}
const result = fn(arg);
cache[arg] = result;
return result;
};
}Higher-order function to limit search API calls