How to check for “undefined” value in JavaScript ?
In JavaScript, undefined
is a primitive value that represents the absence of a value or the uninitialized state of a variable. It’s typically used to denote the absence of a meaningful value, such as when a variable has been declared but not assigned a value. It can also indicate the absence of a return value in a function or the absence of a defined property in an object. Understanding undefined
is crucial for writing robust and error-free JavaScript code.
There are a few ways to check for ‘undefined’.
- Using the ‘typeof’ operator
- Comparing with the ‘undefined‘ value
1. Using the ‘typeof’ operator:
Here, ‘typeof‘ operator returns the string ‘undefined’ if the variable has not been assigned a value.
// Declare a variable
let myVariable;
// Condition to check variable is defined or not
if (typeof myVariable === "undefined") {
console.log("myVariable is undefined");
} else {
console.log("myVariable is defined");
}
Output
myVariable is undefined
Comparing with the ‘undefined’ value
Here, the ‘===’ operator checks if the value of the variable is exactly equal to ‘undefined’.
// Declare a variable
let myVariable;
// Condition to check variable is defined or not
if (myVariable === undefined) {
console.log("myVariable is undefined");
} else {
console.log("myVariable is defined");
}
Output
myVariable is undefined
Example 1:
// Using the 'typeof' operator:
// Declare a variable
let fruit;
// Condition for check variable is defined or not
if (typeof fruit === "undefined") {
console.log("fruit is undefined");
} else {
console.log("fruit is defined");
}
Output
fruit is undefined
Example 2:
// Using the 'typeof' operator:
// Declare a variable and assign a value
// it will return fruit is defined
let fruit = "apple";
// Condition for check variable is defined or not
if (typeof fruit === "undefined") {
console.log("fruit is undefined");
} else {
console.log("fruit is defined");
}
Output
fruit is defined
Example 3:
// Comparing with the 'undefined' value:
// Declare a variable
let profile;
// Condition for check variable is defined or not
if (profile === undefined) {
console.log("profile is undefined");
} else {
console.log("profile is defined");
}
Output
profile is undefined
Example 4:
// Comparing with the 'undefined' value:
// Declare a variable and assign value
let profile = "w3wiki";
// Condition for check variable is defined or not
if (profile === undefined) {
console.log("profile is undefined");
} else {
console.log("profile is defined as", profile);
}
Output
profile is defined as w3wiki
Contact Us