Karolina Kaszuba Personal Dev Blog

Tricky case when passing a function as a callback

May 16, 2021

Tricky case when passing a function as a callback

When we want to pass a function as a callback to e.g. Array.map() method we usually pass it inline and everything works as expected.

const myArray = [1, 2, 3];
const newArray = myArray.map((element) => element * 2);
console.log(newArray); // output: [2, 4, 6]

But we can also pass a previously defined function, or a built-in function like parseInt() to parse strings into numbers. And this is the tricky case.

const myArray = ["1", "2", "3"];
const newArray = myArray.map(parseInt);
console.log(newArray); // output: [1, NaN, NaN]

Here we can see an unexpected result. You might have expected to get [1, 2, 3], but we get [1, NaN, NaN]. We need to remember that the callback function in a map method can accept up to three arguments. And parseInt() function takes two arguments (string and radix). So, the map method passed two arguments to it, not one, and that caused the problem. The third argument was unused in this case.

const myArray = ["1", "2", "3"];
const newArray = myArray.map((currentValue, index, array) => {
  // parseInt(string, radix);
  return parseInt(currentValue, index);
});
console.log(newArray); // output: [1, NaN, NaN]

/*  first iteration  (index is 0): */ parseInt("1", 0); // 1
/*  second iteration (index is 1): */ parseInt("2", 1); // NaN
/*  third iteration  (index is 2): */ parseInt("3", 2); // NaN
Reminder » What is a radix? A value between 2 and 36 that specifies the base of the number. If this argument is not supplied to the function parseInt(string, radix), strings with a prefix of 0x are considered hexadecimal. All other strings are considered decimal. So keep in mind that decimal is not default in all situations.

One way to fix such a situation is to use an arrow function that explicitly calls parseInt() with only one argument that we need.

const myArray = ["1", "2", "3"];
const newArray = myArray.map((num) => parseInt(num));
console.log(newArray); // output: [1, 2, 3]

Overall, such a tricky case is also possible with other methods like Array.forEach(), which callback also accepts up to three arguments. And the callback function does not need to be built-in, it can also be defined by us, so we need to be aware of this tricky case if our function takes more than one argument.


Profile picture

Written by Karolina Kaszuba - Software Developer and Designer who lives and works in a beautiful city of Gdańsk, Poland.