An open source JavaScript project I work on includes code:
if (color) { tapeDiv.style.backgroundColor = color; // set color here if defined by event. Else use css }
A contributor wants to change it to
if (color != null) { // this line changed tapeDiv.style.backgroundColor = color; // set color here if defined by event. Else use css }
color is a string var. Only a string of more than 0 characters should be used to explicitly set the color.
Since JS casts ” and null as boolean false, why would the comparison != null be needed?
Am I missing something in thinking that the first form is just as good (and a bit shorter) than the second?
I see comparisons with null quite often in JS source. Why are they needed when all JS simple objects have known results when cast as booleans?
Thanks,
Larry
ps. I suppose if 0 (an integer) was a valid case, then if(0) would be false [a problem] and if(0 != null) would be true [allows the 0 case]. Any other reason?
pps. Should have mentioned that the tapeDiv is newly created. So there’s no point to resetting the style to ” since the div is brand new.
No, and your ps is correct. Null would evaluate to false, and if null needs to be distinguished from empty string or 0, then you’d do the null check.
Or it could just be for clarity. It’s more descriptive to indicate that you’re specifically looking for null.