How to check for “undefined” value in JavaScript ?
Last Updated :
14 Mar, 2023
In JavaScript, ‘undefined’ is a primitive value that represents a variable that has been declared but has not been assigned a value, a function that has no return statement, or an object property that does not exist.
There are a few ways to check for ‘undefined’.
Approach 1: Using the ‘typeof’ operator:
Syntax:
Javascript
let myVariable;
if ( typeof myVariable === "undefined" ) {
console.log( "myVariable is undefined" );
} else {
console.log( "myVariable is defined" );
}
|
Here, ‘typeof’ operator returns the string ‘undefined’ if the variable has not been assigned a value.
Output:
myVariable is undefined
Approach 2: Comparing with the ‘undefined’ value:
Syntax:
Javascript
let myVariable;
if (myVariable === undefined) {
console.log( "myVariable is undefined" );
} else {
console.log( "myVariable is defined" );
}
|
Here, the ‘===’ operator checks if the value of the variable is exactly equal to ‘undefined’.
Output:
myVariable is undefined
Example 1:
Javascript
let fruit;
if ( typeof fruit === "undefined" ) {
console.log( "fruit is undefined" );
} else {
console.log( "fruit is defined" );
}
|
Output:
fruit is undefined
Example 2:
Javascript
let fruit = "apple" ;
if ( typeof fruit === "undefined" ) {
console.log( "fruit is undefined" );
} else {
console.log( "fruit is defined" );
}
|
Output:
fruit is defined
Example 3:
Javascript
let profile;
if (profile === undefined) {
console.log( "profile is undefined" );
} else {
console.log( "profile is defined" );
}
|
Output:
profile is undefined
Example 4:
Javascript
let profile = "geeksforgeeks" ;
if (profile === undefined) {
console.log( "profile is undefined" );
} else {
console.log( "profile is defined as" , profile);
}
|
Output:
profile is defined as geeksforgeeks
Share your thoughts in the comments
Please Login to comment...