Question about "undefined" in Javascript

Today one of my friends said:

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

      

- such a code is entered by a beginner and writes

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

      

I initially think there must be some difference. But I can't seem to find the difference. Is there anything in there? Or are the two examples the same?

Thank.

+1


source to share


4 answers


Have a look at the Javascript question , check if a variable is an object , but note that Tom Ritter's accepted answer looks incomplete , check the comment on his answer. See also the community answer Rob .



+2


source


If isoft

must contain a reference to an object, both do the same. A is !isoft

true for all false values, but the object cannot be false.



+1


source


There is little difference in the regular objects example you provided. However, another typical pattern might 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 to true when no radio buttons were found (radioButtons.length is 0) and create an array of one (nonexistent) radio button. The same problem can arise if you decide to handle the switches using:

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

      

There are other examples containing empty strings where if (!variable)

it is probably not recommended and it is better to test it with typeof undefined or check for null explicitly.

+1


source


There is no significant difference in your specific example, since you are evaluating an object instance and objects are converted to Boolean true when cast to Boolean, whereas undefined and null are evaluated as Boolean false. But take this as 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 love making shortcuts and preserving typing wherever I am, of course, but you should know when to make shortcuts and when not;)

+1


source







All Articles