( 0 || something ) in Javascript - "Logical Or" Bug
Today I remembered something that bothered me during my first days of writing javascript. A line of code that created a bug that took me a long time to detect thinking that this "buggy" line could never be the reason for the problem.
Here's a simple example to demonstrate the dilemma I had.
function incrementCounter(input, override) {
return override || ++input || 0;
}
This method increments a certain input integer, tries to increment it or return 0 if NaN. If an override value is provided then it returns this value.
Let's take a look at some outputs with different inputs.
incrementCounter()returns0
incrementCounter(1)returns2
incrementCounter(1, 5)returns5
Everything is fine and according to plan until now.
But...
incrementCounter(1, 0)returns2
Yes 2 ! not 0. Why is that?
In javascript, zero evaluates to false when using logical or || operations. That means 0 || 'anything' will return 'anything'. For those coming from Ruby background, this makes no sense at all. In Ruby, this will return 0.
That is a mistake that some developers could fall into and take time to debug.
To make the piece of code above work correctly, we need to separate the comparison to 0 so that we return it when specified as the override.
function incrementCounter(input, override) {
if(override == 0) { return 0; }
return override || ++input || 0;
}
This exactly returns the expected output.