Wednesday, 5 July 2017

How to determine whether an object has a given property in JavaScript



How can I determine whether an object x has a defined property y, regardless of the value of x.y?



I'm currently using




if (typeof(x.y) !== 'undefined')


but that seems a bit clunky. Is there a better way?


Answer



Object has property:



If you are testing for properties that are on the object itself (not a part of its prototype chain) you can use .hasOwnProperty():




if (x.hasOwnProperty('y')) { 
// ......
}


Object or its prototype has a property:



You can use the in operator to test for properties that are inherited as well.



if ('y' in x) {

// ......
}

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...