title: Check if a property is in a Object tip-number: 10 tip-username: loverajoel tip-username-profile: https://www.twitter.com/loverajoel tip-tldr: These are ways to check if a property is present in an object. tip-writer-support: https://www.coinbase.com/loverajoel
When you have to check if a property is present in an object, you probably are doing something like this:
var myObject = { name: '@tips_js'};if (myObject.name) { ... }
That’s ok, but you have to know that there are two native ways for this kind of thing, the in
operator and Object.hasOwnProperty
. Every object descended from Object
, has both ways available.
var myObject = { name: '@tips_js'};myObject.hasOwnProperty('name'); // true'name' in myObject; // truemyObject.hasOwnProperty('valueOf'); // false, valueOf is inherited from the prototype chain'valueOf' in myObject; // true
Both differ in the depth at which they check the properties. In other words, hasOwnProperty
will only return true if key is available on that object directly. However, the in
operator doesn’t discriminate between properties created on an object and properties inherited from the prototype chain.
Here’s another example:
var myFunc = function () { this.name = '@tips_js';};myFunc.prototype.age = '10 days';var user = new myFunc();user.hasOwnProperty('name'); // trueuser.hasOwnProperty('age'); // false, because age is from the prototype chain
Check the live examples here!
I also recommend reading this discussion about common mistakes made when checking a property’s existence in objects.