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.

Advertisements

One thought on “How to Test Properties in JavaScript Object

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s