Detecting an undefined object property
Detect an undefined property in JavaScript using typeof. If the property does not exist or is undefined, typeof will output "undefined":
Here, '?' is known as the optional chaining operator which safeguards against a TypeError if obj is undefined.
Striding through undefined: your toolset
To navigate the undefined landscape effectively, here are some tried and tested tools you should always keep at your disposal.
hasOwnProperty - your property owner investigator
Use obj.hasOwnProperty('prop') when you need to confirm whether a property exists on an object without considering the prototype chain.
The untouchable undefined in ES5 and beyond
Post ES5, undefined is an immutable standard value. However pre-ES5, void 0 was used frequently as a secure way to get the undefined value; today it serves as a historical reminder of JavaScript's dynamic evolution.
Undefined, defined? typeof is your answer
Whether a variable is declared or not, typeof will safely return 'undefined' if it holds no value. If in doubt, typeof is your scout.
JavaScript scope: named undefined variables
Be careful out there, because JavaScript allows local variables to be named undefined, which can end up hiding the global undefined. Keep a keen eye on the scope!
Playing "hide-and-seek" with properties using in
The in operator does a thorough job when checking for property existence, diving into the prototype chain too, unlike hasOwnProperty.
Keep those traps at bay: common pitfalls and solutions
Let's go through some common mistakes you could make while dealing with undefined properties and learn how to avoid them.
That falsy booby trap
Beware, if(obj.prop) checks for other falsy values—'', 0, null, not just undefined. Explicitness is your best bet in JavaScript.
The undeniable power of triple equals
A direct obj.prop === undefined check is clean when looking for explicit undefined properties. It's like stating loudly, "I want to see your ID".
null vs undefined: the battle of missing values
Remember, null and undefined are almost twins in JavaScript—null == undefined. So when a property's null, it's a significant absence of value.
Was this article helpful?