In JavaScript, null
is a special value that represents the intentional absence of any object value. It is a primitive data type often used when a variable is expected to have an object but currently does not.
JavaScript includes null
as one of its primitive values, along with undefined
, boolean
, number
, string
, and symbol
. Understanding how to handle null
properly helps prevent errors and ensures your code runs smoothly.
There are many ways to check for nulls in JavaScript. In this post, we will see four ways to check for nulls.
Methods to check for nulls
- Using strict equality operator
- Using nullish coalescing operator (??)
- Using typeof operator
- Using object.is()
Related Articles:
Method 1 – Using strict equality operator
The strict equality operator in JavaScript is denoted by ===
. It is used to compare two values for equality without performing type coercion. This means that not only must the values be equal, but they must also have the same data type.
if(value === null) {
// value is null
} else {
// value is not null
}
If block condition will pass only for null and will not pass if the value is “”, undefined, false, 0 or NaN.
Method 2 – Using nullish coalescing operator (??)
The nullish coalescing operator (??
) is a relatively recent addition to JavaScript, introduced with ECMAScript 2020 (ES11). It provides a concise way to handle the case where a value might be null
or undefined
, and you want to use a default value if the variable is nullish.
let value = null;
let result = value ?? "CodeyMaze";
If value is null, result will be set to CodeyMaze
Method 3 – Using typeof operator
The typeof
operator in JavaScript is a unary operator that is used to determine the data type of a given expression. It returns a string indicating the type of the operand.
if(typeof value == 'object' && value == null) {
// value is null
} else {
// value is not null
}
Using typeof method, first will check if the value is of type null, if yes then checking for null value.
Method 4 – Using object.is()
Object.is()
is a static method introduced in ECMAScript 2015 (ES6) to provide a more reliable way to compare values for equality in JavaScript. This method provides a strict equality comparison.
let value = null;
if(Object.is(value, null)) {
// value is null
} else {
// value is not null
}
Wrapping Up
In this tutorial, we used four approaches to check for nulls in javascript.
In the first approach, we used a strict equality operator. In the second approach, we used nullish coalescing operator (??).
In the third approach, we used typeof with equality check. In the fourth approach, we make use of object.is() method.