How to detect an undefined object property in JavaScript

October 14, 2022 No comments javascript object undefined object-property

Introduction

In JavaScript, we may wish to detect an undefined object property. In this post, we'll look at how to do it.

How to detect an undefined object property in JavaScript

To detect an undefined object property in JavaScript we need to use typeof and compare it with undefined as a string:

const person = {
    name: "Alan",
    age: 34
};

console.log(person.surname); // undefined

console.log(typeof person.age === 'undefined'); // false
console.log(typeof person.surname === 'undefined'); // true

This is the most reliable method.

Conclusion

In this post, we presented the best and most reliable way to detect an undefined object property in JavaScript.

{{ message }}

{{ 'Comments are closed.' | trans }}