This blog will discuss the methods for determining whether a variable is null or empty.
How to Check if a Variable is Null or Empty in JavaScript?
For verifying whether the variable is null or empty, you can use the following methods:
- length property
- strict equality (===) with OR (||) operator
Let’s go through the working of these methods individually.
Method 1: Check if a Variable is Null or Empty Using length Property
To verify whether a variable is null or empty, you can use the “length” property, which is the fundamental property of JavaScript. It is possible to perform self-reflection in JavaScript functions that interact with other functions by using the length property
Syntax
Follow the below-given syntax for the length property:
Here, we will check if the length of the variable “val” is zero or not.
Example
In this example, we will create an empty string stored in a variable “val”:
Then, we will use the length property in a conditional statement to check if the length of the variable is 0, representing that it is an empty string:
console.log("variable ‘val’ is empty");
}
Execute the above code and see the output:
Let’s move to the next method!
Method 2: Check if a Variable is Null or Empty Using strict equality (===) and OR (||) Operator
Another method to verify the variable is null or empty is using the strict equality “===” operator with OR “||” operator. The strict equality operator checks the two operands of different types and returns a boolean value true if they are the same.
Syntax
You can use the following syntax for checking the variable is null or empty:
Example
Here, we will create a variable “val” and assigned a “null” value to it:
Then, we will use the OR operator with strict equality operator in the “if” conditional statement to verify whether the variable is null or empty:
console.log("variable is null");
}
The output indicates that the variable “val” is null:
We have presented all the methods to check if a variable is null or empty in JavaScript.
Conclusion
For verifying whether the variable is null or empty, you can use the length property of the JavaScript or the strict equality (===) operator with the OR (||) operator in JavaScript. The length property is mainly used for the empty variables because the empty variables contain 0 lengths while null shows the absence of object value. In this blog, we have discussed the methods for checking the variable, whether it is null or empty or not.