JavaScript undefined Property

JavaScript undefined is a property used to express a specified value that is not defined. The undefined is a primitive value and property of the global object which means it can be accessed and used directly. The undefined property can be used in different cases in most of the checking if a variable is defined or undefined.

Check If Variable Is Undefined with Strict Equality

By using the undefined property a variable can be checked if it is defined or not. Event the variable can be created but a value is not set for this variable. In this case, the variable is called is undefined.

var a;

if(a === undefined){
   console.log("Variable is undefined")
}
else{
   console.log("Variable is defined")
}

The output is like the below because the variable is not defined or set a value.

Variable is undefined

Check If Variable Is Undefined with typeof Operator

Another way to check if a variable is defined or undefined is using the typeof operator. the variable type can be checked with the typeof operator and return ‘undefined’ if the variable value is not set.

var a;

if(typeof a === 'undefined'){
   console.log("Variable is undefined")
}
else{
   console.log("Variable is defined")
}

Check If Variable Is Undefined with void Operator

The void operator is used to specify void or undefined values. The void 0 can be used to check an undefined variable.

var a;

if(a === void 0){
   console.log("Variable is undefined")
}
else{
   console.log("Variable is defined")
}

Check If Variable Is Undefined with window Object

Most of the variables and objects are defined under the window object and the window can be used to access these variables or objects.

var a;

if(window.a){
   console.log("Variable is undefined")
}
else{
   console.log("Variable is defined")
}

Leave a Comment