How to Check if a Property Exists in a JavaScript Object

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.

Follow me on Twitter: https://twitter.com/AuMayeung

Image for post
Image for post

Written by

Web developer. Subscribe to my email list now at http://jauyeung.net/subscribe/. Email me at hohanga@gmail.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store