How to Check If a Variable Is/Is Not Null in JavaScript

Not quite sure how to check if a variable is (or isn’t) null in JavaScript? Don’t worry, we got you. This guide will show you the ropes.

Published Categorized as JavaScript, Web & Code

In JavaScript, null is a primitive value intended to represent the purposeful absence of any value for a given object.

If you call a variable and it has the value null, this means that the variable has been declared, but no data has been assigned to it. Simply put, it’s like an empty placeholder for data.

Check If a Variable Is Null

The best way to check if a variable is null in JavaScript is using an if statement with the strict equality operator (===).

if (myVariable === null) {
    /* Do this if variable is null */
}

Don’t use the equality operator (=) because it can return false positives when the value of your variable is false, 0, "" (an empty string), null, undefined, or NaN. The strict equality operator (===) doesn’t have this problem because it checks against the value and the type of the two operands.

Check If a Variable Is Not Null

The best way to check if a variable is not null in JavaScript is using an if statement with the strict inequality operator (!==).

if (myVariable !== null) {
    /* Do this if variable is not null */
}

Don’t use the inequality operator (!=) because it can return false positives when the value of your variable is not false, 0, "" (an empty string), null, undefined, or NaN. The strict inequality operator (!==) doesn’t have this problem because it checks against the value and the type of the two operands.

By Dim Nikov

Editor of Maker's Aid. Part programmer, part marketer. Making things on the web and helping others do the same since the 2000s. Yes, I had Friendster and Myspace.

Leave a comment

Your email address will not be published. Required fields are marked *