Emmanuel Akinfulubi

JavaScriptFunction

Pass a function as an argument in JavaScript

Intermediate · 4 min read

In JavaScript, a function is a value, just like a number or a string. You can store it in a variable, put it in an array, and pass it into another function. That one idea is behind map, filter, reduce, every click handler and every callback you will ever write.

In this tutorial you will pass a function into another function and call it. Then you will build on that: forward any number of arguments, return new functions, add logging to a function without changing it, and make a function remember its answers. You need to know what a function is and how arrow functions look.

Functions are values

Write a function's name without brackets and you get the function itself. Add brackets and you call it, getting back its result:

JavaScript

const double = (n) => n * 2;
console.log(typeof double);    // 'function'
console.log(typeof double(5)); // 'number'
console.log(double(5));        // 10

That difference, double versus double(5), is the key to this whole exercise.

Higher-order functions

A function that takes another function as an argument, or returns one, is called a higher-order function. You have probably used one already:

JavaScript

console.log([1, 2, 3].map(double)); // [2, 4, 6]

map is higher-order. You hand it double, and it calls double once for each item.

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

28 Pass a function as a parameter

fair

Pass one function into another and call it. Then look at what makes that useful.

Stuck? Three hints, smallest first
  1. 1. Pass the function itself, not a call: run(double), not run(double()).
  2. 2. A function that takes or returns a function is called higher-order.
  3. 3. ...args lets a wrapper forward whatever it is given.

Step 1: pass a function and call it

The plainest version takes a function and a value, and calls one with the other:

Step 1

const apply = (fn, value) => fn(value);
const shout = (s) => s.toUpperCase();
console.log(apply(double, 5));       // 10
console.log(apply(shout, 'lagos'));  // 'LAGOS'

apply doesn't know or care what fn does. The same line works for numbers and for text.

Step 2: the classic mistake

It is easy to add brackets by habit:

Step 2

try {
  apply(double(5), 5);
} catch (e) {
  console.log(e.name); // 'TypeError'
}

double(5) runs straight away and gives 10. So apply receives the number 10 as fn, and calling 10(5) fails. Pass double, not double(5).

Step 3: forward any number of arguments

Some functions need more than one argument. ...args in the parameter list collects every extra argument into an array, called a rest parameter. ...args in a call spreads them back out:

Step 3

const callWith = (fn, ...args) => fn(...args);
console.log(callWith(Math.max, 1, 9, 4)); // 9
console.log(callWith(() => 'ok'));         // 'ok'

This is what a wrapper needs: a function that sits around another one and passes everything through.

Step 4: return a function

A function can also build and return a new function. twice takes fn and returns a function that calls fn two times:

Step 4

const twice = (fn) => (x) => fn(fn(x));
console.log(twice(double)(5)); // 20
const compose = (...fns) => (x) => fns.reduceRight((value, fn) => fn(value), x);
console.log(compose(double, (n) => n + 1)(5)); // 12
console.log(compose((n) => n + 1, double)(5)); // 11

compose joins several functions into one, running them from right to left, like reading double(addOne(5)). The order matters: adding one and then doubling gives 12, doubling and then adding one gives 11.

Step 5: add something without changing the function

A decorator is a function that takes a function and returns a new one with the same behavior plus something extra. logged records every call:

Step 5

function logged(fn) {
  const calls = [];
  const wrapped = (...args) => {
    const result = fn(...args);
    calls.push({ args, result });
    return result;
  };
  wrapped.calls = calls;
  return wrapped;
}
const loggedDouble = logged(double);
loggedDouble(2);
loggedDouble(3);
console.log(loggedDouble(10));         // 20: same answers as double
console.log(loggedDouble.calls.length); // 3
console.log(loggedDouble.calls[0]);     // { args: [2], result: 4 }

Functions are objects too, so you can attach a property like calls to them. The original double is untouched.

Step 6: remember answers

Memoization means saving a function's results so the same input is never worked out twice. It is the same shape as logged, with a Map as the memory:

Step 6

function memoise(fn) {
  const cache = new Map();
  let misses = 0;
  const wrapped = (n) => {
    if (cache.has(n)) return cache.get(n);
    misses++;
    const value = fn(n);
    cache.set(n, value);
    return value;
  };
  wrapped.misses = () => misses;
  return wrapped;
}
const slowSquare = memoise((n) => n * n);
slowSquare(4); slowSquare(4); slowSquare(5);
console.log(slowSquare(4));       // 16
console.log(slowSquare.misses()); // 2

Four calls, but only two real calculations, one for 4 and one for 5. For a slow function, that saving is the whole point.

Step 7: passing a method can lose its object

One more trap. When you pull a method off an object and pass it around, it forgets which object it belongs to:

Step 7

const arr = [1, 2];
const join = arr.join;
try { join(','); } catch (e) { console.log(e.name); } // 'TypeError'
console.log(join.bind(arr)(','));          // '1,2'
console.log(((...a) => arr.join(...a))(',')); // '1,2'

bind(arr) makes a copy of the function that is tied to arr. A small arrow function that calls arr.join works too.

The full solution

The panel has every piece: apply, callWith, twice, compose, logged and memoise. It prints each one in action, then shows that double(5) is a number, not a function. Press Run to see the output.

The answer

// The plainest version.
const apply = (fn, value) => fn(value);

const double = (n) => n * 2;
const shout = (s) => s.toUpperCase();

// Forwarding any number of arguments, which is what a wrapper needs.
const callWith = (fn, ...args) => fn(...args);

// Returning a function: this is where higher-order functions earn their keep.
const twice = (fn) => (x) => fn(fn(x));
const compose = (...fns) => (x) => fns.reduceRight((value, fn) => fn(value), x);

// A decorator: same behaviour, plus a record of the calls.
function logged(fn) {
  const calls = [];
  const wrapped = (...args) => {
    const result = fn(...args);
    calls.push({ args, result });
    return result;
  };
  wrapped.calls = calls;
  return wrapped;
}

// Memoising: same idea, and it is why passing functions around matters.
function memoise(fn) {
  const cache = new Map();
  let misses = 0;
  const wrapped = (n) => {
    if (cache.has(n)) return cache.get(n);
    misses++;
    const value = fn(n);
    cache.set(n, value);
    return value;
  };
  wrapped.misses = () => misses;
  return wrapped;
}

console.log('apply(double, 5)      =', apply(double, 5));
console.log('apply(shout, "lagos") =', apply(shout, 'lagos'));
console.log('callWith(Math.max, 1, 9, 4) =', callWith(Math.max, 1, 9, 4));
console.log('twice(double)(5)      =', twice(double)(5));
console.log('compose(double, double)(5) =', compose(double, double)(5));

const loggedDouble = logged(double);
loggedDouble(2); loggedDouble(3);
console.log('logged calls:', loggedDouble.calls);

const slowSquare = memoise((n) => n * n);
slowSquare(4); slowSquare(4); slowSquare(5);
console.log('memoised: 3 calls,', slowSquare.misses(), 'actual computations');

console.log('--- the classic mistake ---');
console.log('passing double(5) instead of double gives', typeof double(5), '- a number, not a function');

Output


      
19 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 19 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

19 checks

test('a function can be passed and called', apply(double, 5), 10);
test('and a different one', apply(shout, 'lagos'), 'LAGOS');
test('several arguments can be forwarded', callWith(Math.max, 1, 9, 4), 9);
test('with none at all', callWith(() => 'ok'), 'ok');
test('a function is a value, so typeof says function', typeof double, 'function');
test('while calling it gives a number', typeof double(5), 'number');
test('a function returning a function applies it twice', twice(double)(5), 20);
test('and three times if nested', twice(twice(double))(1), 16);
test('compose runs right to left', compose(double, (n) => n + 1)(5), 12);
test('which is not the same as left to right', compose((n) => n + 1, double)(5), 11);
test('the logged wrapper returns the same answers', loggedDouble(10), 20);
test('and recorded every call', loggedDouble.calls.length, 3);
test('with the arguments', loggedDouble.calls[0].args, [2]);
test('and the results', loggedDouble.calls[0].result, 4);
test('memoising returns the same values', slowSquare(4), 16);
test('but computes each input only once', slowSquare.misses(), 2);
test('even after repeated calls', (() => { slowSquare(4); slowSquare(5); return slowSquare.misses(); })(), 2);
test('a built-in method can be passed too', [1, 2, 3].map(String), ['1', '2', '3']);
test('though a method losing its receiver is a real hazard', (() => { const f = [1, 2].join; try { return f(','); } catch (e) { return e.constructor.name; } })(), 'TypeError');

The mechanical answer is one line. What makes it worth an exercise is everything built on it: map, filter, reduce, every event listener, every callback. Functions being values is the feature.

logged and memoise are the same shape — take a function, return a function with the same behaviour plus something extra. That is a decorator, and the assertion showing slowSquare computed only two distinct inputs across four calls is the payoff.

Two traps in the assertions. compose runs right to left, and the two orderings give different answers, so the direction is a decision to document. And the last one: pulling a method off an object with const f = [1, 2].join loses the receiver, so calling f(',') throws — pass (...a) => arr.join(...a) or use .bind(arr). This is the most common way passing a function goes wrong in practice.

Common mistakes

  • Passing double(5) instead of double. The brackets call the function, so you pass its result. Leave them off.
  • Forgetting that compose runs right to left. Swapping the order of the functions can change the answer.
  • Passing a method on its own. const f = arr.join loses arr. Use arr.join.bind(arr) or (...a) => arr.join(...a).

Try it yourself

  1. Use apply with Math.sqrt and 81. You should get 9.
  2. Write thrice(fn) that calls fn three times, and check thrice(double)(1) gives 8.
  3. Wrap shout with logged, call it twice, and print the calls array.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.