Categories
JavaScript Answers

How to determine if an object property exists and is not empty with JavaScript?

Spread the love

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 toundefinedwitherrors.error2 !== undefined`.

Conclusion

To determine if an object property exists and is not empty with JavaScript, we can use the hasOwnProperty method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *