How to Check if a Variable is Undefined in Javascript
To check if a variable is undefined in Javascript you can use the typeof
operator or just the variable itself. For an undefined variable, the variable will return undefined
. The typeof
operator will also return a value of undefined
.
An undefined variable in Javascript is a variable that has been declared but has not been assigned a value.
If the variable is defined, it will return one of the remaining data types in Javascript.
Example Code
var futureSocialMediaCompanyName;
console.log(futureSocialMediaCompanyName);
console.log(typeof(futureSocialMediaCompanyName));
Result
Check Javascript Variables Using Conditionals
In most instances, you will be checking whether avariable is undefined using conditionals like if
, if else
, while
and do while
.
To check if variable is strictly equal to undefined
regardless of whether it has been declared or not, use typeof variable === 'undefined'
.
Code
var futureSocialMediaCompanyName;
if (futureSocialMediaCompanyName === undefined) {
console.log('Variable is undefined');
} else {
console.log('Do something else if variable is defined');
}
Using typeof operator, you get:
if (typeof(futureSocialMediaCompanyName) === 'undefined') {
console.log('Variable is undefined');
} else {
console.log('Do something else if variable is defined');
}
Result
The difference between typeof variable === 'undefined'
and variable === undefined
is that if variable has not been declared, variable === undefined
throws ReferenceError while typeof
does not.
Check Javascript Variables Using Functions
Using type of operator, your code will be:
var futureSocialMediaApp;
var currentSocialMediaApp = 'TikTok';
function checkIfVarUndefined(app){
if ( typeof(app) === 'undefined') {
console.log('Variable is undefined');
} else {
console.log('Variable is defined');
}
}
checkIfVarUndefined(futureSocialMediaApp);
checkIfVarUndefined(currentSocialMediaApp);
You can work without using the typeof operator:
var futureSocialMediaApp;
var currentSocialMediaApp = 'TikTok';
function checkIfVarUndefined(app){
if (app === undefined) {
console.log('Variable is undefined');
} else {
console.log('Variable is defined');
}
}
checkIfVarUndefined(futureSocialMediaApp);
checkIfVarUndefined(currentSocialMediaApp);
Result