How to Check Null Value in JavaScript

To check a null value in JavaScript, you can use the “strict equality operator ( === )” operator. The strict equality operator checks value and type, ensuring the variable is null and not another false value (e.g., undefined, false, 0, or an empty string).

Syntax

if (variable === null) {
  // variable is null
} else {
  // variable is not null
}

This method is the most accurate way to check for null values since it checks both value and type, ensuring that the variable is null and not another false value (e.g., undefined, false, 0, or an empty string).

Example

const nullValue = null;
const undefinedValue = undefined;
const emptyString = '';

if (nullValue === null) {
  console.log('nullValue is null');
} else {
  console.log('nullValue is not null');
}

if (undefinedValue === null) {
  console.log('undefinedValue is null');
} else {
  console.log('undefinedValue is not null');
}

if (emptyString === null) {
  console.log('emptyString is null');
} else {
  console.log('emptyString is not null');
}

Output

nullValue is null
undefinedValue is not null
emptyString is not null

In this example, the strict equality operator (===) function checks if nullValue, undefinedValue, and emptyString are null.

It returns true only for nullValue and false for the other two variables since they have different values and types.

Using the strict equality operator (===) for precise comparisons in JavaScript is recommended.

Leave a Comment