In JavaScript there are 2 distinct scenarios when the object property can be undefined. Let’s look into them and find out how to check for undefined fields in JS objects.
The object property is either missing or equal to undefined
The most basic check for an undefined
object property is an equality operator.
if (obj.property === undefined)
An alternative is the checking the type of the object property with the typeof
operator. In this case
you need to wrap 'undefined'
in single quotes as typeof
returns a string.
if (typeof obj.property === 'undefined')
Here’s how you can use it in a real world scenario. Let’s check if the user’s surname is undefined
:
const user = {
age: 25,
name: 'Jack',
}
if (typeof user.surname === 'undefined') {
console.log('surname is undefined');
}
Note that you can’t just write
if (!obj.property)
As it will work the same way for all falsy values in JavaScript.
const user = {
age: 25,
name: 'Jack',
isLearning: false,
address: null,
email: ''
}
console.log(!user.surname); // true
console.log(!user.isLearning); // true
console.log(!user.address); // true
console.log(!user.email); // true
In all these cases, you’ll get true
, which means that you can’t reliably use the negation operator !
as an
undefined check in JavaScript.
The object property is present, but its value is undefined
When you’re looking to check if a specific property is present in a JavaScript object, but its values was
explicitly set to undefined
, you should use a different approach.
Let’s consider another object.
const task = {
requested_by: 34589,
status: undefined,
}
And you’re looking to check for 2 properties: status
and deadline
.
The check should return true
only if an object has a given property, and it’s equal to undefined
.
const task = {
requested_by: 34589,
status: undefined,
};
if (Object.keys(task).includes('status') && typeof task.status === 'undefined') {
console.log('Task status is present and equal to undefined');
}
You can make this code reusable by wrapping it in a function.
const hasUndefinedProperty = (obj, key) => Object.keys(obj).includes(key) && typeof obj['key'] === 'undefined';