Search code examples
javascriptvariablesshort-circuiting

JavaScript OR (||) Short Circuit Strange Behavior


I am writing a small function that takes in a parameter and attempts to call parseInt(value) || value.toUpperCase() but it is failing to work as expected with certain values.

function convert(value)
{
    return parseInt(value) || value.toUpperCase();
}

Some example outputs are
convert("asdf") -> "ASDF"
convert("Car") -> "CAR"
convert("1") -> 1
convert("52") -> 52

But for some reason when I input "0" I am getting "0" back out. I've attempted to call parseInt("0") and it is correctly parsing 0 out, but when coupled with the || "0".toUpperCase() it is always returning the string "0".

The only excuse I can come up with is that 0 || "0" always resolved to "0" because it is treating 0 as undefined or null (which my understanding was that the short-circuit evaluation of JavaScript was only short-circuited with undefined, null, or false values).

I hope someone could provide me a little bit of clarity regarding this issue.


Solution

  • 0 is falsy, so the other expression in the logical || will be evaluated. That is why you are getting "0". You can confirm that like this

    1 || console.log("First");
    0 || console.log("Second");
    # Second
    

    Since 1 is truthy, it short circuits and doesn't execute the console.log("First"), but 0 is falsy so it goes ahead and executes console.log("Second")