- JavaScript
- JavaScript Fundamentals for Frontend Interviews
- Higher Order Functions
Higher Order Functions in JavaScript: 3 Patterns
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};67function add(a, b) {8 return a + b;9}10const loggedAdd = withLog(add);11loggedAdd(2, 3);1213const 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);1819const multiplyBy = (x) => (y) => x * y;20const triple = multiplyBy(3);21console.log(triple(5), [1, 2].map(triple).join(' '));
Predict Console Output
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.
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.
- Wrapping (decorators):
withLog(fn)returns a new function that callsfnand adds logging. The same pattern gives youmemoize,debounce,onceand retry helpers. The wrapper keepsfnthrough a closure. - Passing behaviour in:
filter,mapandreducetake callbacks and do the looping for you. Order matters:filterruns first, so only 2 and 4 are multiplied and summed. - Function factories:
multiplyBy(3)returns a function specialised by its argument.tripleremembersx = 3, and because it is a value it can be passed straight tomap. 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.
What is the difference between a higher order function and a callback?
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.
Why can JavaScript have higher order functions?
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.
What are common examples of higher order functions?
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.
How do closures relate to higher order functions?
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.
What is a decorator or wrapper function?
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.
Why does [1, 2, 3].map(parseInt) return [1, NaN, NaN]?
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
