Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu January 08, 2023 › #HowTo #Javascript

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>
But if you check whether the country property exists in the obj object, it will be false because the object does not have the country property.

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>
save
listen
AI Answer
Write Your Answer
loading
back
View All