Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing for undefined in JavaScript

I want to run a code only if the argument[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?

like image 904
Asim Zaidi Avatar asked Dec 22 '22 01:12

Asim Zaidi


2 Answers

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 )
like image 102
Peter Bailey Avatar answered Jan 14 '23 11:01

Peter Bailey


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)
like image 36
Felix Kling Avatar answered Jan 14 '23 13:01

Felix Kling