Functions as callbacks risks

Abdallah Hemdan
4 min readFeb 15, 2021

Hello everyone šŸ‘‹, This article is a summary of Jake Archibaldā€™s (Software Engineer at Google) article ā€œDonā€™t use functions as callbacks unless theyā€™re designed for itā€ which posted on 29 January 2021.

The article discusses the point of using functions as callbacks may lead us to unexpected behavior/output which is different from our expectation, let us see how that may happen So without further ado, Letā€™s Get It Started šŸƒā€ā™‚ļø

šŸ¦ŗ Safe usage

Let us imagine that we are using toReadableNumber function (converts input numbers into human-readable string form) from some-library as a callback function that has the following implementation:

And toReadableNumber has the following implementation:

So far everything works great until the maintainers of some-library decide to update the implementation of toReadableNumber and add another parameter (base) to convert the number to a readable one with specific radix with a default value of 10 to make toReadableNumber function backward-compatible with the old usage.

šŸ“Œ The root of all evil

After the maintainer updated the function and you didnā€™t change anything in your implementation but the following will happen:

Actually, besides the number itself, Weā€™re also passing the index of the item in the array, and the array itself

By using toReadableNumber as a callback, we have assigned the index to the base parameter which will affect the output of the toReadableNumber function.

The developers of toReadableNumber felt they were making a backward-compatible change but it breaking our code, mainly it isnā€™t some library's fault ā€” they never designed toReadableNumber to be a callback to array.map , they didnā€™t expect that some code would have already been calling the function with three arguments.

šŸ”Ø Best practice

So the safe thing to do is create your own function that is designed to work with array.map And thatā€™s it! The developers of toReadableNumber can now add parameters without breaking our code.

šŸ“ƒ parseInt Example

Let see another example of the result of using functions as a callback, Imagine we have a numList which is a list of string numbers and weā€™d like to parse its items to integers.

- Mmmmm, sounds easy, let us use parseInt šŸ˜Ž!

It seems EASY but in case you used parseInt as a callback function, you will be shocked! if you used parseInt as a callback you will get [-10, Nan, 2, 6, 12] while we are expecting [-10, 0, 10, 20, 30], thatā€™s because parseInt has a second parameter which is the radix

šŸ”Ø Solution

It is better to call the function explicitly instead of passing the function reference directly.

šŸ“ Linting rules

Using eslint-plugin-unicorn you can add Prevent passing a function reference directly to iterator methods to your set of eslint rules

Thank you for your reading, See you later šŸ™

--

--