Higher Order Functions in JavaScript: 3 Patterns

Easy100% Free~14 mins#higher-order-functions#first-class-functions#closures#map-filter-reduce#decorator
Interview Answer (30-Second Summary)

Higher order functions in JavaScript are functions that take another function as an argument, return a function, or both. map, filter, reduce, setTimeout and addEventListener take functions; function factories and decorators return them. They work because functions are first-class values, and the returned functions keep access to their outer variables through closures.

Key Learning Objectives
✓

Define a higher order function and spot one in everyday code.

✓

Write a wrapper (decorator) that adds behaviour to any function.

✓

Chain filter, map and reduce and predict the result.

✓

Build function factories and explain how closures keep their arguments.

The Interview Problem

What do the three lines of output say?

1const withLog = (fn) => (...args) => {
2 const result = fn(...args);
3 console.log(`${fn.name}(${args.join(', ')}) = ${result}`);
4 return result;
5};
6
7function add(a, b) {
8 return a + b;
9}
10const loggedAdd = withLog(add);
11loggedAdd(2, 3);
12
13const total = [1, 2, 3, 4]
14 .filter((n) => n % 2 === 0)
15 .map((n) => n * 10)
16 .reduce((sum, n) => sum + n, 0);
17console.log(total);
18
19const multiplyBy = (x) => (y) => x * y;
20const triple = multiplyBy(3);
21console.log(triple(5), [1, 2].map(triple).join(' '));
Predict Console Output
Interactive Challenge

Select the option that matches what this code prints to the console:

add(2, 3) = 5 / 60 / 15 3 6

anonymous(2, 3) = 5 / 60 / 15 3 6

add(2, 3) = 5 / 100 / 15 3 6

add(2, 3) = 5 / 60 / NaN 3 6

V8 Engine Execution Trace
Step 1 of 6 (Line 10)

withLog takes a function and returns a new one. The returned wrapper keeps fn = add in its closure.

Call Stack (Top = Active)
Global
withLog(add)
Lexical Scope / Bindings
fn:add
loggedAdd:(...args) => { ... }
Console Stream
> [empty]

Higher Order Functions in JavaScript Explained

Higher Order Functions in JavaScript, Three Ways

A higher order function takes a function, returns a function, or both. JavaScript allows it because functions are first-class values.

  1. Wrapping (decorators): withLog(fn) returns a new function that calls fn and adds logging. The same pattern gives you memoize, debounce, once and retry helpers. The wrapper keeps fn through a closure.
  2. Passing behaviour in: filter, map and reduce take callbacks and do the looping for you. Order matters: filter runs first, so only 2 and 4 are multiplied and summed.
  3. Function factories: multiplyBy(3) returns a function specialised by its argument. triple remembers x = 3, and because it is a value it can be passed straight to map. Passing functions this way needs care when the callee sends extra arguments: ['1', '2', '3'].map(parseInt) gives [1, NaN, NaN] because map also passes the index.
Common Traps & Mistakes

Passing the result of a call instead of the function: map(triple()) instead of map(triple).

Passing a function that takes optional extra parameters, such as parseInt, straight to map.

Forgetting the initial value in reduce, which breaks on an empty array.

FAANG Follow-Up Probes
Probe #1

Implement your own map and filter on Array.prototype.

Probe #2

Write once(fn), which runs fn only on the first call and returns the same result afterwards.

Probe #3

Write compose(f, g, h) so that compose(f, g, h)(x) is f(g(h(x))).

Higher Order Functions in JavaScript Interview Questions

Key interview inquiries, edge cases, and architectural follow-ups for Higher Order Functions.

Q1.
What is a higher order function in JavaScript?

A function that takes a function as an argument, returns a function, or both. Array.prototype.map is one because it takes a callback; multiplyBy is one because it returns a new function.

The higher order function is the one receiving or returning a function; the callback is the function passed in. In [1, 2].map(triple), map is the higher order function and triple is the callback.

Functions are first-class values: they can be stored in variables, passed as arguments, returned and given properties, just like objects. That is what makes withLog(add) and multiplyBy(3) possible.

Array methods (map, filter, reduce, some, every, find, sort with a comparator), timers (setTimeout), event listeners (addEventListener), Promise.then, and utilities such as debounce, memoize, curry and compose.

A function returned from a higher order function keeps access to the variables of the call that created it. triple remembers x = 3, and loggedAdd remembers fn = add, long after multiplyBy and withLog have returned.

A higher order function that takes a function and returns a new one with extra behaviour, such as logging, timing, caching or retrying, while calling the original. withLog is a small decorator.

map passes three arguments to its callback: value, index and array. parseInt takes (string, radix), so it receives parseInt('2', 1) and parseInt('3', 2), which are NaN. Use map((s) => parseInt(s, 10)) or map(Number).

More JavaScript interview questions for freshers