LAST UPDATED: MARCH 1, 2023
JavaScript Program To Check If A Variable Is undefined or null
JavaScript is a widely-used programming language for creating interactive web pages and applications. Variables are used to store data that can be accessed and modified later in JavaScript. Occasionally, however, these variables may be null or their value may be unknown. This can lead to code errors and cause the application to crash.
Therefore, it is essential to determine whether a variable has a value prior to using it. In this article, we will discuss how to determine if a JavaScript variable is undefined or null.
We also have an interactive JavaScript course where you can learn JavaScript from basics to advanced and get certified.
Program To Check If A Variable Is undefined or null
In the code given below, a variable is checked if it is equivalent to null
. The null
with ==
checks for both null
and undefined
values. This is because null == undefined
evaluates to true.
// JavaScript Program to check if a variable is undefined or null
function checkVariable(variable) {
if(variable == null)
console.log('The variable is undefined or null');
else
console.log('The variable is neither undefined nor null');
}
let newVariable;
checkVariable(50);
checkVariable(1.5);
checkVariable("JavaScript is the world's most popular programming language.");
checkVariable(null);
checkVariable(newVariable);
The variable is neither undefined nor null
The variable is neither undefined nor null
The variable is neither undefined nor null
The variable is undefined or null
The variable is undefined or null
Program To Check If A Variable Is undefined or null using typeof Operator
The typeof operator for undefined value returns undefined. Hence, you can check the undefined value using typeof operator. Also, null values are checked using the === operator. We cannot use the typeof
operator for null
as it returns an object.
// JavaScript Program to check if a variable is undefined or null
function checkVariable(variable) {
if( typeof variable === 'undefined' || variable === null )
console.log('The variable is undefined or null');
else
console.log('The variable is neither undefined nor null');
}
let newVariable;
checkVariable(5);
checkVariable(1.5);
checkVariable("JavaScript is the world's most popular programming language.");
checkVariable(null);
checkVariable(newVariable);
The variable is neither undefined nor null
The variable is neither undefined nor null
The variable is neither undefined nor null
The variable is undefined or null
The variable is undefined or null
Conclusion
In conclusion, it is necessary to determine whether a variable has a value before utilizing it in JavaScript. Errors in the code can be caused by undefined and null values, which can also cause the program to crash. In this article, we discussed how to use a hook and the typeof operator to determine whether a JavaScript variable is undefined or null.