Question

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.

Was it helpful?

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")

OTHER TIPS

I think what you actually want to do is this:

return isNaN(value) ? value.toUpperCase() : parseInt(value);

Explanation: this checks, whether value can be converted to a Number and then returns the appropriate conversion.

As you stated yourself, 0 is treated as false (it's falsy). Since it's false, the expression on the right is evaluated, and the uppercase version of "0" obviously is the same.

What exactly are you trying to do using || value.toUpperCase() there?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top