How to Check Null Value in Javascript

Checking for null values is a simple task that every developer has to perform at some point or another. The typeof operator helps in checking null because the keyword returns “object” for null, so that means a little bit more effort is required.

The value null is falsy, but empty objects are truthy, so typeof nullValue === “object” && !nullValue is a simple approach to check that a value is not null. But what is null? Let’s check it out.

What is null?

The null value in JavaScript describes the intentional absence of any object value. It is one of JavaScript’s primitive values.

This distinguishes null from the similar primitive value undefined, an unintentional absence of any object value.

The null is a falsy value because it evaluates to false if compelled to a boolean.

Javascript null check

To check a null value in JavaScript, use the equality operator ( == ). The equality operator ( == ) in JavaScript checks whether its two operands are equal, returning a Boolean result. Unlike the strict equality operator, it attempts to convert and compare operands of different data types.

Syntax

if (variable == null){
 // your code here.
}

See the following code example.

let data = null

if (data == null) {
 console.log("The data is null")
}
else {
 console.log("The data is not null")
}

Output

The data is null

That’s it. The above code successfully checks whether the variable is null or not.

Check null and undefined in JavaScript

To check null and undefined simultaneously in a single code, use the OR( || ) operator.

The null value is only loosely equal to itself and undefined, not to the other falsy values shown.

let data = undefined

if (data == null || data == undefined) {
 console.log("The data is null or undefined")
}

else {
 console.log("The data is not null or undefined")
}

Output

The data is null or undefined

This way, you can check both null and undefined at the same time.

Comparing == vs === when checking for null

Comparisons can be made: null === null to check strictly for null or null == undefined to check loosely for either null or undefined.

That’s it for checking null in the JavaScript tutorial.

Leave a Comment