Node.js
Higher-order functions
Learn functions that take functions as parameters.
Higher-order functions
A higher-order function either takes a function as a parameter or returns a function. Functions that accept callbacks fall in this category; but those that return functions are just as important.
Example: function makeAdder(n) { return (m) => n + m; }. This function takes a number and returns another function. The returned function remembers n and adds the new parameter m: const add5 = makeAdder(5); add5(3) gives 8.
This pattern is also called a closure; the returned function remembers variables from where it was defined. You will see the details at the advanced level.
Closure in brief
A function 'remembers' the variables from the scope where it was defined. This is called a closure. Higher-order functions use it to carry outer values into the function they return.
Example: function makeMultiplier(factor) { return (x) => x * factor; }. Here makeMultiplier(3) returns a function that remembers factor as 3. That function later computes x * 3.
A closure creates a separate environment per call. makeMultiplier(3) and makeMultiplier(5) produce two independent functions with different factor values. This is what makes higher-order functions flexible.
Exercise Return a multiplier function
Define a function makeMultiplier(factor). Its body returns the arrow function (x) => x * factor. Build a multiplier with const triple = makeMultiplier(3), then print the result of triple(7) with console.log.
Show example solution
function makeMultiplier(factor) {
return (x) => x * factor;
}
const triple = makeMultiplier(3);
console.log(triple(7));
Test yourself
-
Add with a closure
function makeAdder(n) {
return (m) => n ____ m;
}
Show answer
function makeAdder(n) {
return (m) => n + m;
}
-
Which is a higher-order function?
- function add(a, b) { return a + b; }
- function make(fn) { return fn; }
- const x = 5;
- const arr = [1, 2, 3];
Show answer
function make(fn) { return fn; } — make takes a function parameter and returns a function.
-
Match the HOF parts
- makeAdder
- HOF name
- n
- Outer parameter
- (m) => n + m
- Returned function
- add5(3)
- Call giving 8
Next lesson: forEach with callbacks