I am peer reviewing code written in vanilla javascript, and one of the authors occasionally performs a lazy-typecast if
statement because he is evaluating values from a REST service that has very sloppy data. Occasionally a value representing money in USD comes back as a string, and sometimes as a number, probably depending on what validation was in place at the time the user entered the data over the years.
So sometimes we get a value of 150
and sometimes we get "150"
(without the quotes, if you know what I mean).
The data is just displayed, and there are no math operations done against it: it simply needs to be compared to another number so some display styling can be done.
Instead of writing some function that checks the type of data and forces it to be a uniform type, the developer does something like this:
var baseVal = ReturnsAnIntegerValue(); // returns a number
var retrievedVal = CallToAwfulDataService(); // could return number or string
if (retrievedVal && retrievedVal == baseVal) {
// do stuff
}
else { ...
At first the ==
made me see a red flag, but when I asked him about it, he said that the initial check for if (retrievedVal && ...
would prevent unexpected outcomes from situations where baseVal
and retrievedVal
are each some combination of null
, 0, empty string, or undefined
, like this:
if (null && null == undefined) // false | if (null == undefined) // true
if (0 && 0 == "") // false | if (0 == "") // true
if (0 && 0 == "0") // false | if (0 == "0") // true
if (0 && 0 == "") // false | if (0 == "") // true
You get the idea. I feel like this should be bad code because I was taught that the ==
is bad form, but the code is readable and concise, without the need for an extra function that type-converts just for show. I can't think of a scenario where we are likely to be hurt by it.
Is this bad code? Specifically: what is wrong with it? Is there a better practice for handling this?
edit
I forgot to mention, I have looked at a bunch of SO questions that mostly seem to back up the ==
is code smell school of thought, but I can't see what is technically risky about this scenario.