tags:

views:

211

answers:

3

Today one of my friends said:

if (typeof isoft == "undefined") var isoft = new Object();

is such kind of code is writted by a freshman and writes

if(!isoft) var isoft = new Object();

I originally consider there must be some difference. But I can't find the difference. Is there any? Or are the two examples the same?

Thanks.

+1  A: 

If isoft should hold a reference to an object, both do the same. A !isoft is true for all false values, but a object can't be a false value.

stesch
+2  A: 

See the question Javascript, check to see if a variable is an object but note that the accepted answer by Tom Ritter appears to be incomplete, check the comment on his answer. See also the community answer by Rob.

Sam Hasler
+1  A: 

In the example involving regular objects that you provided there is little difference. However, another typical pattern can be:

var radioButtons = document.forms['formName'].elements['radioButtonName'];
if ('undefined' === typeof radioButtons.length) {
    radioButtons = [ radioButtons ];
}
for (var i = 0; i < radioButtons.length; i++) {
    // ...
}

If you used if (!radioButtons.length) it would evaluate true when no radio buttons were found (radioButtons.length is 0) and create an array of a single (non-existent) radio button. The same problem can arise if you choose to handle the radio buttons using:

if ('undefined' === typeof radioButtons.length) {
    // there is only one
} else {
    // there are many or none
}

There are other examples involving empty strings where if (!variable) is probably not recommended and it is better to test against typeof undefined or explicitly test against null.

Grant Wagner