While working with JavaScript objects you may come across a common scenario that whether object contains property with specific or given name or not?
You can do this with following options
- in operator
- hasOwnProperty() method
- propertyIsEnumerable() method
Consider following object student
var student = { name: "dj", grade: 10 };
in operator
You can apply in operator on student object whether that name is its property as following
You will get true as output because name is property of object student.
- in operator returns true for own property
- in operator returns false if there is no property with given name
- in operator returns true for inherited property
Following code will return true because toString is inherited property of student.
hasOwnProperty() method
Now to check given name property exist or not you can apply hasOwnProperty() method as following
You will get true as output because name is property of object student.
- hasOwnProperty() method returns true for own property
- hasOwnProperty() method returns false if there is no property with given name
- hasOwnProperty() method returns false for inherited property
So following code will return false because toString is inherited property.
propertyIsEnumerable() method
It works exactly the same way of hasOwnProperty() method with one exception that it will return false for own property of object which is not enumerable .
In this way you can check for property in JavaScript. I hope you find this post useful. Thanks for reading.
Filed under: JavaScript
