Categories
JavaScript

How to Check if a Property Exists in a JavaScript Object

Spread the love

Since JavaScript allows you to create dynamic objects, you have to be careful and check if an object’s property actually exists. There are at least 2 ways to do this.

hasOwnProperty

hasOwnProperty is a function built into all objects.

if (obj.hasOwnProperty('prop')) {  
    // do something  
}

Note: Internet Explorer host objects (objects supplied by the environment and are different between browsers) do not have the hasOwnProperty function.

in Operator

in is a built in operator you can use to check for an existence of an object property.

if ('prop' in obj) {  
    // do something  
}

Note: obj ‘s prorotypes will also be checked for the prop property.

Undefined Check

You can check if an object has a property by checking if it’s undefined :

if (typeof obj.prop !== 'undefined') {  
  // do something  
}

or:

if (typeof obj['prop'] !== 'undefined') {  
  // do something  
}

You have to use triple equals so that it won’t check for other falsy values.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *