Functions as callbacks risks
Hello everyone ??, This article is a summary of Jake Archibald's (Software Engineer at Google) article "Function callback risks"
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 ??