
How to Check if a Property Exists in a JavaScript Object
In this article, you will learn how to check if a property exists in a JavaScript object using the hasOwnProperty() Method.
Syntax of the hasOwnProperty() method.
obj.hasOwnProperty(name)
The hasOwnProperty() method checks whether a property exists in a JavaScript object and returns true if it exists or false if it doesn't.
Suppose you have the below object with two properties and you want to check if the property called age exists in the obj object.
let obj = { name : 'John', age : 45, }
So, to check if the obj object contains the age property, you need use the hasOwnProperty() method, like this. This would return true because the age property exists in the obj object.
<script> let obj = { name : 'John', age : 45, } let a = obj.hasOwnProperty('age'); console.log(a); </script>
Now, in this example, we will alert a message if the obj object has an age property otherwise not.
if(obj.hasOwnProperty('age')){ alert('age property exists.') }
How to Check if a Property Exists in an Object using undefined #
If we try to access the country property, it returns undefined because the country property doesn't exist in the obj object.
<script> let obj = { name : 'John', age : 45, } if(obj.country == undefined){ alert('Property undefined!') } </script>