Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the correct way to test for existence of a property on a JavaScript Object?

Tags:

I have a custom Javascript object that I create with new, and assign properties to based on creation arguments:

function MyObject(argument) {     if (argument) {         this.prop = "foo";     } } var objWithProp = new MyObject(true); // objWithProp.prop exists var objWithoutProp = new MyObject(false); // objWithoutProp.prop does not exist 

What's the correct way to test for the existence of the prop property of the objects? I've seen the following ways used, but I'm not sure if any of these ways is the best way:

  • if (obj.prop) {}
  • if (obj.hasOwnProperty("prop")) {}
  • if ("prop" in obj) {}

Specifically, I'm only interested in testing if the property is explicitly defined for this object, not in the prototype chain. In addition, the value will never be set to null or undefined, but it could be something like an empty object or array. However, if you want to include what the correct way is if those could be the case, feel free.

like image 572
Rudd Zwolinski Avatar asked May 22 '09 04:05

Rudd Zwolinski


1 Answers

hasOwnProperty is exactly what you're looking for, since you specify "if the property is explicitly defined for this object, not in the prototype chain". Per https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object/hasOwnProperty , "This method can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check down the object's prototype chain." -- seems to exactly match your requirement!

like image 141
Alex Martelli Avatar answered Nov 20 '22 06:11

Alex Martelli