How to detect an undefined object properties in JavaScript?

This short tutorial is about checking if object property is undefined in JavaScript.

There are many ways in javascript to detect an undefined object value. However, the proper and correct way to detect would be using the typeof operator.

The typeof operator returns a string indicating the data type of the unevaluated operand. The operand can be an object, string, function, or any other variable.


typeof operand

Detect undefined property using typeof operator:

if (typeof myVar === "undefined")

This will return us the correct result, it will also handle the situation where the property is not declared.

Wht not to use === operator ?

Since undefined is not a JavaScipt keyword we can assign a value to it.

So if we give a falsy value to undefined and use === to check if it's undefined or not, it will give us a false result.

Let's see the example below.

var undefined = false;  // assigned a falsy to the variable undefined
if (myVar === undefined) {
    console.log("This correct but not true");

And if the myVar property is undeclared then it will raise an error too.

So, it's better to use the typeof operator as it will give the correct results and will handle the above-mentioned error.

💾 Recommended Articles