JavaScript: Checking Property Existence

, , …,

There are 2 important distinction of properties:

Check If a Object Has Own Property

obj.hasOwnProperty("pName") → return true if the property named pName is obj's own property, else false. If the property doesn't exist, return false.

// Example of using ‹obj›.hasOwnProperty(‹prop name›)

var o1 = {"p":1};

// create a object o2, with parent o1
var o2 = Object.create(o1);

console.log(o1.hasOwnProperty("p")); // true
console.log(o2.hasOwnProperty("p")); // false

// none existent property
console.log(o2.hasOwnProperty("yyy")); // false

Check If a Object is in Prototype Chain

To check if a property is in a object's prototype chain (including if it's its own property), use the in operator.

"property name" in object → return true if property name is object's own property, or if property name is a property of some object in object's prototype chain.

// example of using 「"‹p›" in ‹o›」

var o1 = {"p1":1};

// create a object o2, with parent o1
var o2 = Object.create(o1);

o2["p2"] = 2;

console.log("p1" in o2)         // true
console.log("p2" in o2)         // true

// non-existent property
console.log("yyyyy" in o1)         // false
console.log("yyyyy" in o2)         // false

Note: the syntax p in o is not a part of the syntax for (var p in o) {…}. They look the same but don't have the same meaning. The for loop goes thru all enumerable properties in the object and its prototype chain. 〔☛ JavaScript: Property, Prototype Chain, Enumerable: Accessing & Listing Properties

blog comments powered by Disqus