Home > JavaScript, jQuery > JavaScript: How to determine whether a variable has a valid value

JavaScript: How to determine whether a variable has a valid value

November 29th, 2012 Leave a comment Go to comments

    A good way to examine whether a variable (or object’s field) has a valid value looks like the following:

if( variable /* obj.field */ ) {

This statement allows to check if the value is null (explicit assignment of null to variable happened) or undefined (variable wasn’t initialized). To be more precise it returns true when the variable is not

  • null
  • undefined
  • NaN
  • empty string (“”)
  • 0
  • false

Mostly, such validity check is more than enough for further safe treating with the variable. However, we’ll get the “‘variable’ is undefined error” if the variable is undeclared. In this case we have to perform the following check in advance:

if(typeof variable !== 'undefined') {    

Of course, if you are pretty sure that the variable exists (is declared), you can omit the typeof check. But if you deal with something going from an external library or source, I recommend having it. So, gathering all together, we obtain the following code:

if(typeof variable !== 'undefined' && variable) {    

In some forums, people from time to time suggest to wrap such check into a function. Let’s assume we have such function:

function isValid(obj) {    
  return typeof obj !== 'undefined' && obj;

However, it doesn’t make sense at all as you can’t call the function, passing an undeclared variable, in any case. The mentioned above error is thrown whenever you try addressing to the unknown variable:

if(isValid(varibale)) // throw "'variable' is undefined error", 
                      // if the variable doesn't exist

Thus, in case of undeclared variable, we have to have inline typeof check. In all other cases, it’s enough to have simple if(variable). So, using variables and objects likely declared outside of my code, I examine them like in the sample below:

if(typeof navigator != "undefined" && navigator && navigator.userAgent)
Categories: JavaScript, jQuery Tags: ,
  1. No comments yet.
  1. No trackbacks yet.