Signup/Sign In

How to determine if variable is undefined or null in JavaScript?

Answer: Using equality (==) operator or strict equality (===) operator

In JavaScript, if a variable is declared but any value is not assigned to it then the default value of that variable is undefined. So whenever we print the value of that variable, the output will be undefined.

Example

In the given example, we have created two variables x and y. We have assigned 5 to variable x and no value assigned to variable y. When we try to print the value of both variables we get 5 as the value of x and undefined keyword as the value of y.

var x = 5; 
console.log(x);
var y; 
console.log(y);

Output


5
undefined

While the null is a keyword, that can be assigned to a variable. The null keyword represents no existence of any value.

In simple words, we can say that the term undefined represents that a variable is declared but any value is not assigned yet while the null keyword represents the no value.

We can check whether the variable is undefined or null using the equality (==) operator or strict equality operator.

Example: Using equality (==) operator

In the given example, we have used the equality (==) operator to check whether the element is null or undefined or not.

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>Determine if variable is null or undefined</title>
</head>
<body>
	<script>
		var var1;
		var var2 = null;

		console.log(null == undefined)  
		console.log(null === undefined) 

		if(var1 == null){
		    console.log('Variable "var1" is undefined.');
		} 
		if(var2 == null){
		    console.log('Variable "var2" is null.');
		}
	</script>
</body>
</html>

Output

image

Example: Using strict equality (===) operator

In the given example, we have checked the strict equality (===) operator to check whether the element is null or undefined or not.

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>Determine if variable is null or undefined</title>
</head>
<body>
	<script>
		var var1;
		var var2 = null;		
		
		if(var1 === undefined) {
		    console.log("True");
		} 
		if(var2 === null){
		    console.log("True");
		}
	</script>
</body>
</html>

Output

image

Conclusion

In this lesson, we have explained how to find out whether the element is defined or null. So we used the equality operator or strict equality operator. The equality operator compares the variable with null or undefined keywords and returns the output.



About the author: