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
}

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
}

Undefined Check

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

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

Web developer. Subscribe to my email list now at https://thewebdev.info/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