简体   繁体   中英

A question about “undefined” in Javascript

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.

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 .

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.

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.

In your particular example there's no significant difference, since you're evaluating Object instance, and objects are converted to Boolean true when cast to Boolean, while undefined and null are evaluated as Boolean false. But take this for an example:

function alertSomething(something) {
    //say you wanna show alert only if something is defined.
    //but you do not know if something is going to be an object or
    //a string or a number, so you cannot just do
    //if (!something) return;
    //you have to check if something is defined
    if (typeof something=='undefined') return;
    alert(something);
}

I like to take shortcuts and save typing wherever I can, sure, but you have to know when to take a shortcuts, and when not to ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM