Emmanuel Akinfulubi

JavaScriptBasic

Pass a function as a callback 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 and pass it to another function. A function you pass in so that someone else can call it later is a callback. You already use them: map, filter, sort, setTimeout and every click handler take one.

In this tutorial you will write one function that walks a list of fares and lets the caller decide how each fare is written, by passing a callback. Then you will look at a famous puzzle, ['10', '10', '10'].map(parseInt), which gives [10, NaN, 2], and work out why. You need to know how to write a function and what an array is.

Passing versus calling

The brackets make all the difference:

  • describe is the function itself, a value you can hand over.
  • describe() calls the function right now and gives you its result.

So list.map(describe) gives map the function, and map calls it once per item. list.map(describe()) calls describe once, immediately, with no argument, and gives map whatever came back.

Who owns what

With a callback, the work splits cleanly. The walker owns the loop: going through the list, collecting results. The caller owns the decision: what to do with each item. Change the callback and you get a different output with no second loop.

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

94 Pass a function, do not call it

fair

Write one walker that formats a list and takes the formatting as a callback, so two different outputs need no second walker. Then look at what ['10','10','10'].map(parseInt) returns, and why.

Stuck? Three hints, smallest first
  1. 1. list.map(describe) passes the function; list.map(describe()) calls it far too early.
  2. 2. map hands the callback three arguments: value, index and the whole array.
  3. 3. parseInt takes a second argument, and it is a radix.

Step 1: a walker that takes a callback

Fares are in kobo (100 kobo make one naira). The underscore in 200_00 only makes it easier to read.

Step 1

function summarise(list, describe) {
  return list.map(describe).join(', ');
}
const fares = [200_00, 350_00, 500_00];
console.log(summarise(fares, (kobo) => kobo / 100 + ' naira')); // 200 naira, 350 naira, 500 naira

summarise doesn't know or care how a fare should look. It passes describe straight to map, then joins the results with commas.

Step 2: a different callback, same walker

Now pass a named function that formats naira with a sign and two decimals:

Step 2

function summarise(list, describe) {
  return list.map(describe).join(', ');
}
const SIGN = '\u20a6';
const asNaira = (kobo) => SIGN + (kobo / 100).toFixed(2);
const fares = [200_00, 350_00, 500_00];
console.log(summarise(fares, asNaira)); // ₦200.00, ₦350.00, ₦500.00

'\u20a6' is the naira sign ₦ written as a code, so the file works even where typing it is awkward. Note there are no brackets after asNaira: you are handing the function over, not calling it.

Step 3: calling it too early

Here is the wrong turn, adding brackets by habit:

Step 3

const shout = (text) => text.toUpperCase();
try {
  ['yaba'].map(shout());
} catch (err) {
  console.log(err.name); // TypeError
}

shout() runs immediately with no argument, so text is undefined, and undefined.toUpperCase() throws. Even if it hadn't thrown, map would have received a value instead of a function, and that throws a TypeError too. The fix is map(shout).

Step 4: map passes three arguments

map doesn't call your callback with just the item. It passes the item, its position (index) and the whole array:

Step 4

const out = ['a', 'b'].map((v, i, all) => v + i + all.length);
console.log(out); // [ 'a02', 'b12' ]

For 'a' it called the callback with ('a', 0, ['a', 'b']), giving 'a' + 0 + 2. Most callbacks only take the first argument and ignore the others. That is fine, until the callback does use a second argument.

Step 5: the parseInt puzzle

parseInt(text, radix) reads a number from text. Its second argument, the radix, is the number base: 10 for normal numbers, 2 for binary. Now pass it straight to map:

Step 5

const parsed = ['10', '10', '10'].map(parseInt);
console.log(parsed); // [ 10, NaN, 2 ]

map called parseInt('10', 0), parseInt('10', 1) and parseInt('10', 2). The index landed in the radix slot:

  • Radix 0 means "work it out", which is decimal here: 10.
  • Radix 1 doesn't exist, so the result is NaN ("not a number").
  • Radix 2 reads '10' as binary, which is 2.

Step 6: two safe fixes

Step 6

console.log(['10', '10', '10'].map(Number));                  // [ 10, 10, 10 ]
console.log(['10', '10', '10'].map((s) => parseInt(s, 10))); // [ 10, 10, 10 ]

Number only uses its first argument, so the extra ones can't hurt it. Or wrap parseInt in a small arrow and pass the radix yourself. The rule: passing a function by name is only safe when its extra parameters can't be filled by mistake.

The full solution

The answer panel has summarise with two different callbacks, shows the three arguments map passes, the parseInt result and both fixes, and the TypeError from calling the callback too early. Press Run to see the output.

The answer

const SIGN = '\u20a6';
const fares = [200_00, 350_00, 500_00];

function summarise(list, describe) {
  return list.map(describe).join(', ');
}

const asNaira = (kobo) => SIGN + (kobo / 100).toFixed(2);

const parsed = ['10', '10', '10'].map(parseInt);

// Calling the callback yourself hands map a value, not a function.
const shout = (text) => text.toUpperCase();
let calledTooEarly = '';
try {
  ['yaba'].map(shout());
} catch (err) {
  calledTooEarly = err.name;
}

console.log(summarise(fares, asNaira));
console.log('map(parseInt) gives', parsed);

Output


      
9 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 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('the callback shapes the output', summarise(fares, asNaira), SIGN + '200.00, ' + SIGN + '350.00, ' + SIGN + '500.00');
test('a different callback, the same walker', summarise(fares, (kobo) => kobo / 100 + ' naira'), '200 naira, 350 naira, 500 naira');
test('map hands the callback three arguments, not one', ['a', 'b'].map((v, i, all) => v + i + all.length), ['a02', 'b12']);
test('so parseInt gets the index as its radix: 0 means decimal', parsed[0], 10);
test('radix 1 does not exist, so this one is not a number', Number.isNaN(parsed[1]), true);
test('and radix 2 reads "10" as binary', parsed[2], 2);
test('Number takes one argument, so it is safe here', ['10', '10', '10'].map(Number), [10, 10, 10]);
test('or wrap it and pass the radix yourself', ['10', '10', '10'].map((s) => parseInt(s, 10)), [10, 10, 10]);
test('calling the callback instead of passing it throws', calledTooEarly, 'TypeError');

Taking the formatting as an argument is the whole idea behind map, filter, sort and every event handler: the walker owns the loop, the caller owns the decision. Two outputs, one walker, no duplication.

['10','10','10'].map(parseInt) giving [10, NaN, 2] is the classic demonstration of the trap: map passes three arguments, parseInt accepts two, so the index arrives as the radix. Index 0 means "guess", index 1 is not a legal radix, and index 2 reads the digits as binary. Passing a function by name is only safe when its extra parameters cannot hurt you — hence map(Number) is fine and map(parseInt) is not. And note the missing brackets matter in both directions: map(shout) passes the function, map(shout()) calls it immediately with no argument and hands map the result.

Common mistakes

  • Adding brackets when passing a callback. map(shout()) calls it immediately. Write map(shout).
  • Passing parseInt straight to map. The index becomes the radix. Use map(Number) or map((s) => parseInt(s, 10)).
  • Writing a second loop for a second format. Take the format as a callback instead.

Try it yourself

  1. Call summarise(fares, ...) with a callback that writes each fare as 'cheap' or 'dear' (dear from ₦400).
  2. Write repeat(times, action) that calls action(i) for i from 0 to times - 1.
  3. Predict, then check, what ['1', '2', '3'].map(parseInt) gives.

Keep practising

Newsletter

New writing, when it lands.

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