开发者

Testing for undefined in JavaScript

I want to run a code only if the argume开发者_Go百科nt[0].recordCount is greater than zero or is NOT undefined. However, the code is ran when the argument[0].recordCound alert shows undefined.

if(arguments[0].recordCount > 0 && 
   arguments[0].recordCount !== 'undefined')
{ //if more than 0 records show in bar
                            
    document.getElementById('totalRecords').innerHTML = 
       arguments[0].recordCount + " Records";
}

How can I test for undefined here?


When using undefined as a string you need to do so with the typeof operator.

Also, you should be checking if it's defined before any other checks on the property.

if ( 'undefined' != typeof arguments[0].recordCount && arguments[0].recordCount > 0 )


undefined is a keyword a global variable with constant value, use it without quotes:

if(arguments[0].recordCount > 0 && arguments[0].recordCount !== undefined)

But actually it would be sufficient to test only the first condition:

if(arguments[0].recordCount > 0)

because if recordCount is larger than zero, it is defined anyway.


More common is to switch the conditions and test first whether it is defined, to avoid possible errors in the following tests (not sure if this is necessary here):

if(arguments[0].recordCount !== undefined && arguments[0].recordCount > 0)


To check for a variable to be not null and not undefined,

if(thatVariable) is enough though implicit conversion can cause problem for some cases where thatVariable is empty string, or a boolean, or number 0. If implicit conversion is not the case for our variable, the following would do,

if(arguments[0].recordCount && arguments[0].recordCount > 0)

But the following would be problematic,

if(arguments[0].recordCount !== undefined && arguments[0].recordCount > 0)

Consider,

var undefined = 'surprise' //possible since undefined is not a keyword
if(arguments[0].recordCount !== undefined && arguments[0].recordCount > 0)

Now this 'if' will break even though recordCount is undefined.

One more thing: if(a != null) will also check undefined due to implicit conversion. Hence if(a != null && a != undefined) is redundant

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜