Since the Array Methods lesson you have been writing numbers.filter(...) and putting a function inside the parentheses. Have you wondered how a function can go in there?
It can, because in JavaScript a function is a value, like a number or a piece of text. A function can be stored in a variable, handed to another function, and returned from another function. A function that takes another function or returns a function is called a higher-order function. The map, filter and reduce you already know are higher-order functions, because all three take a function.
Hand a function to another function
The example below picks the even numbers from numbers, then multiplies each of them by 10:
const numbers = [1, 2, 3, 4, 5, 6];
const isEven = (n) => n % 2 === 0;
const multiplier = (factor) => (n) => n * factor;
const result = numbers.filter(isEven).map(multiplier(10));
console.log(result); // [20, 40, 60]
console.log(numbers); // [1, 2, 3, 4, 5, 6]
isEvenis a function that answerstruewhen the number is even.n % 2is the remainder after dividingnby 2. For an even number, that remainder is 0.numbers.filter(isEven)takes the functionisEvenand calls it for every number. The numbers that givetruestay:[2, 4, 6].multipliertakesfactorand returns a new function: the part after the first=>, which is(n) => n * factor. Somultiplier(10)gives the function(n) => n * 10. That new function is what goes tomap, andmapcalls it for each of those even numbers:[20, 40, 60].numbersdoesn't change.filterandmapalways make a new array.
filter and map take a function, and multiplier returns one. So all three are higher-order functions. Here is how to recognise one: a function goes in as an argument, or a function comes out as the result.
Why is it filter(isEven) and not filter(isEven())? You hand the function itself to filter, so isEven is written without (). If you write isEven(), the function runs right away, with no number. Only its result reaches filter, and that result is false, not a function. multiplier(10) is different: it is written with (), because the result of that call is a function.
map, filter and reduce
All three methods take a function, written here as fn:
map(fn)changes every item and keeps the same number of items:[1, 2, 3].map((n) => n * 2)gives[2, 4, 6].filter(fn)filters: only the items that makefnanswertrueare kept.[1, 2, 3, 4].filter((n) => n > 2)gives[3, 4].reduce(fn, start)combines all the items into one value:
const total = [1, 2, 3].reduce((acc, n) => acc + n, 0);
console.log(total); // 6
acc (short for accumulator) is the result so far, and n is the item being processed. acc begins at the starting value, which is the 0 written after the comma. On each turn, the result of acc + n becomes the acc of the next turn: 0 + 1 = 1, 1 + 2 = 3, 3 + 3 = 6. The starting value matters. With a starting value of 0, an empty array gives 0 instead of an error.
The three methods can be chained: the result of one method goes directly into the next method. One example is [1, 2, 3, 4].filter((n) => n > 1).reduce((acc, n) => acc + n, 0). filter keeps [2, 3, 4], then reduce adds those numbers up to 9.
⚠️ When map, filter or reduce don't give you what you want
- Forgetting
returnin a callback with curly braces.[1, 2, 3].map((n) => { n * 2; })gives[undefined, undefined, undefined]. Write(n) => n * 2or(n) => { return n * 2; }. - Thinking
mapchanges the original array.arr.map(fn)written alone does not changearr, and its result is lost. Store the result in a variable, or writereturn arr.map(fn)directly. reducewithout a starting value. If the array is empty, for example becausefilterkept nothing,reducewithout a starting value stops with a TypeError.
TL;DR: A higher-order function is a function that takes another function or returns a function. Three array methods are higher-order functions, because they take a function. map changes every item. filter keeps only the items that make that function answer true. reduce combines all the items into one value, beginning at a starting value such as 0. Hand a function to these methods without () after its name, because () runs the function right away. All three methods give a new array or value, and the original array does not change.
⚡ A function is a value
Write:
const numbers = [1, 2, 3, 4, 5, 6];
const isEven = (n) => n % 2 === 0;
numbers.filter(isEven); // [2, 4, 6]
Meaning: A function can be stored in a variable and handed to another function, like a number or a piece of text. Here isEven is handed to filter. filter calls it for every number, and only the numbers that give true (the even numbers) stay. A function that takes or returns a function is called a higher-order function.
⚡ A function that returns a function
Write:
const multiplier = (factor) => (n) => n * factor;
numbers.filter(isEven).map(multiplier(10)); // [20, 40, 60]
Meaning: multiplier takes factor and returns a new function: the part after the first =>. multiplier(10) gives the function (n) => n * 10, and that new function is what goes to map. map calls it for every even number: [2, 4, 6] becomes [20, 40, 60]. numbers itself doesn't change, because filter and map make a new array.
⚡ When to write ()
Guess first: why is filter(isEven()) wrong?
Because isEven() runs the function right away, with no number. Only its result (false) reaches filter, and filter needs a function.
Meaning: Hand the function to filter without (): filter(isEven). multiplier(10) does use (), because the result of that call is a function.