Sometimes, we want to determine if an object property exists and is not empty with JavaScript.
In this article, we’ll look at how to determine if an object property exists and is not empty with JavaScript.
How to determine if an object property exists and is not empty with JavaScript?
To determine if an object property exists and is not empty with JavaScript, we can use the hasOwnProperty
method.
For instance, we write:
const errors = {
error1: "Error 1 description",
error2: "Error 2 description",
error3: "",
error4: "Error 4 description"
};
if (errors.hasOwnProperty('error2') && errors.error2 !== undefined) {
// ...
}
We call errors.hasOwnProperty
with 'error2'
to check if the error2
property is in errors
.
And then we check if errors.
error2isn't set to
undefinedwith
errors.error2 !== undefined`.
Conclusion
To determine if an object property exists and is not empty with JavaScript, we can use the hasOwnProperty
method.