Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Why compare with null?

Tags:

javascript

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.

like image 942
Larry K Avatar asked Apr 02 '09 00:04

Larry K


1 Answers

Evaluate the assignment with all possible falsy values and you'll get your answer:

tapeDiv.style.backgroundColor = false; // does nothing

tapeDiv.style.backgroundColor = 0;     // sets as "black", 
                                       // but ignored by FF

tapeDiv.style.backgroundColor = null;  // resets the background-color
                                       // to use whatever is defined
                                       // in a stylesheet (if any),
                                       // but ignored by IE.

tapeDiv.style.backgroundColor = '';    // resets the background-color
                                       // to use whatever is defined
                                       // in a stylesheet (if any).

The check for "if (color)" will not let any of them through.

The check for "if (color != null)" will let 1), 2) and 4) through. 1) doesn't do anything, 2) won't work as expected in Firefox, and 4) will always work as expected. However, "works" is dependent on your context (which you did not provide).

Hope that helps.

like image 58
JPot Avatar answered Oct 23 '22 21:10

JPot