JavaScript undefined Property

JavaScript undefined is a property used to express specified value 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 as undefined.

var a;

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

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

Variable is undefined

Check If Variable Is Undefined with typeof Operator

Another ways 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 undefined variable.

var a;

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

Leave a Comment