In this article we will learn how to check if property is undefined
in JavaScript.
It is very common to check if property is undefined
in JavaScript in JavaScript.
Problem
Now we have a problem which is that we want to check if property in object is undefined
or not.
Imagine you have an object like this:
const object = {
name: "John",
age: 30,
country: "USA"
};
And we want to check if age
is undefined
or not.
How to solve this problem?
The solution to this problem is easy, but first we have to make sure that the element already exists in the object, and then check whether it is undefined
or not.
Solution:
As we said before, first we need to check if property is already exists in the object.
And we will use hasOwnProperty
method to check if property is exists or not.
const object = {
name: "John",
age: 30,
country: "USA"
};
console.log(object.hasOwnProperty('age'));
Output
true
Now we want to check if property is undefined
or not.
const object = {
name: "John",
age: 30,
country: "USA"
};
if (object.hasOwnProperty('age')) {
// Check if property is `undefined`
if (object['age'] === undefined) {
console.log(true);
} else {
console.log(false);
}
}
Output
false
The output was false
because age
not undefined
.
Let's change age
value to undefined
and test our code.
const object = {
name: "John",
age: undefined,
country: "USA"
};
if (object.hasOwnProperty('age')) {
// Check if property is `undefined`
if (object['age'] === undefined) {
console.log(true);
} else {
console.log(false);
}
}
Output
true
You may need to repeat the code more than once, so let's create a function that does that for us.
// Create a function
function isUndefined(object, key) {
if (object.hasOwnProperty(key)) {
if (object[key] === undefined) {
return true;
}
return false;
}
return false;
}
// Object
const object = {
name: "John",
age: undefined,
country: "USA"
};
// Tests
console.log(isUndefined(object, 'name'));
console.log(isUndefined(object, 'age'));
console.log(isUndefined(object, 'country'));
Output
false
true
false
The hasOwnProperty()
method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it). MDN
Thank you for reading
Thank you for reading my blog. 🚀