Friday, 10 October 2014

How to check for null, undefined, or blank variables in JavaScript?

You can just check if the variable has a true value or not. That means

if( value ) {
}

will evaluate to true if value is not:

  • null
  • undefined
  • NaN
  • empty string ("")
  • 0
  • false

Furthermore, if you don't know whether a variable exists (that means, if it was declared) you should check with the typeof operator. For instance

if( typeof foo !== 'undefined' ) {
    // foo could get resolved and it's defined
}

If you can be sure that a variable is declared at least, you can directly check if it has a true value.

Truth, Equality and JavaScript

JavaScript Coercion Demystified

No comments:

Post a Comment