Skip to content

September 8, 2015

Javascript: How to really check for an object property exists

by Joe Kuan

In Javascript, undefined is a value and it can be assigned to properties. So strictly speaking, we shouldn’t use undefined to check for whether an object’s property is defined.

var foo = new Object();
foo.fieldUndefined = undefined;

Here are the results from running on a browser console.
screen
As we can see, both fieldUndefined and fieldNotExist properties show undefined value but fieldUndefined does actually exist.

Some people have suggested to use typeof to check for the type. If it returns undefined, then the field doesn’t exist.
screen
However, this doesn’t work either.

The only way to test an object property actually existed is via Object.hasOwnProperty.
screen

Just make sure no one up your object’s prototype chain has overridden the method which is bad practice. Alternatively, uses Object.prototype.hasOwnProperty.call instead.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Note: HTML is allowed. Your email address will never be published.

Subscribe to comments

%d bloggers like this: