How to Check if a Variable Is Not Null in JavaScript

Harshit Jindal Feb 02, 2024
  1. the Incorrect Way That Seems Right
  2. the Correct Way to Check Variable Is Not Null
How to Check if a Variable Is Not Null in JavaScript

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.

Harshit Jindal avatar Harshit Jindal avatar

Harshit Jindal has done his Bachelors in Computer Science Engineering(2021) from DTU. He has always been a problem solver and now turned that into his profession. Currently working at M365 Cloud Security team(Torus) on Cloud Security Services and Datacenter Buildout Automation.

LinkedIn

Related Article - JavaScript Variable