Check if a Variable Is Not Null in JavaScript

  1. the Incorrect Way That Seems Right
  2. the Correct Way to Check Variable Is Not Null

This tutorial teaches how to check if a variable is not null in JavaScript.

the Incorrect Way That Seems Right

if (myVar) {...}

This way will evaluate to true when myVar is null, but it will also get executed when myVar is any of these:

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

the Correct Way to Check Variable Is Not Null

if (myVar !== null) {...}

The above code is the right way to check if a variable is null because it will be triggered only in one condition - the variable is actually null.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - JavaScript Variable

  • Check if Variable Exists in JavaScript
  • Static Variables in JavaScript