Quantcast
Channel: hasOwnProperty – Dhananjay Kumar
Viewing all articles
Browse latest Browse all 4

How to Test Properties in JavaScript Object

0
0

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

  1. in operator
  2. hasOwnProperty() method
  3. 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

image

You will get true as output because name is property of object student.

  1. in operator returns true for own property
  2. in operator returns false if there is no property with given name
  3. in operator returns true for inherited property

Following code will return true because toString is inherited property of student.

image

hasOwnProperty() method

Now to check given name property exist or not you can apply hasOwnProperty() method as following

image

You will get true as output because name is property of object student.

  1. hasOwnProperty() method returns true for own property
  2. hasOwnProperty() method returns false if there is no property with given name
  3. hasOwnProperty() method returns false for inherited property

So following code will return false because toString is inherited property.

clip_image002

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

Viewing all articles
Browse latest Browse all 4

Latest Images

Trending Articles





Latest Images