Tech Talk : JavaScript – Universal Method To Check For NullI am sure every JavaScript programmer has been faced with this problem. How do you check for all combination of null in a string variable. I thought it would be nice to have a single line of code to do just. It also makes for easier code management and debugging would be a breeze.
I stumbled upon an article in StackOverflow of something that does just that. This is a repost from that article.

Here We Go
The single way to do it is to check for truth value or not. See code below.

if( value ) {

The above code will check for for the following “value” conditions

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

The above list represents all possible false values in ECMA-/JavaScript. Find it in the specification at the ToBoolean section.
However, if you are not too sure if this variable (“value”) has been define or not but must check for the above list of conditions, use the following code.

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