How do I check for null values in JavaScript?

How do I check for null values in JavaScript?
How do I check for null values in JavaScript?

In JavaScript, you can check for null values using the == or === operator, or by using the typeof operator.

Using the == operator:

if (myVar == null) {
    // myVar is either null or undefined
}

Using the === operator

if (myVar === null) {
    // myVar is only null
}

You can also use the typeof operator to check if a variable is null:

if (typeof myVar === 'object' && myVar === null) {
    // myVar is null
}

Alternatively, you can also use the Object.is(myVar, null) method to check if a variable is null.

if (Object.is(myVar, null)) {
    // myVar is null
}

Please keep in mind that while checking if a variable is null, it’s also common to check if it’s undefined too. Since null and undefined are two distinct values in JavaScript, sometimes you will want to check for both.

if (myVar == null) {
    // myVar is either null or undefined
}

or

if (myVar === null || typeof myVar === 'undefined') {
    // myVar is either null or undefined
}

or

if (Object.is(myVar, null) || myVar === undefined) {
    // myVar is either null or undefined
}

In this way, you can handle both cases of null and undefined at the same time.

Leave a Reply