How to Check if a Property is Undefined in JavaScript
Nov 24, 2021
To check if an object property key
was equal to undefined
you can do:
if (obj[key] === undefined) {
// ...
}
The potential problem with this approach approach is that if obj
doesn't have the property, it will also return true.
Checking if the property exists
To check if the object has the property, you can use in
operator or hasOwnProperty()
function.
These paths will tell you if the object property exists on the object.
const obj = { name: 'masteringjs.io', location: 'Florida', helpful: true };
'building' in obj; // false
obj.hasOwnProperty('building'); // false
obj.building === undefined; // true
You can combine these two sections to check if an object has a property and that property is undefined
:
function hasUndefinedKey(obj, key) {
return key in obj && obj[key] === undefined;
}
or
function hasUndefinedKey(obj, key) {
return obj.hasOwnProperty(key) && obj[key] === undefined;
}
More Fundamentals Tutorials
- Convert a Set to an Array in JavaScript
- What Does Setting the Length of a JavaScript Array Do?
- Get the Last Element in an Array in JavaScript
- Skip an Index in JavaScript Array map()
- Conditionally Add an Object to an Array in JavaScript
- Validate Emails using Regex in JavaScript
- JavaScript Copy to Clipboard