Check if an object exists in JavaScript

There’s a few different ways to check if an object exists in JavaScript. If the check is done incorrectly it will cause an error. In some situations a user will be alerted that an error has occurred with the JavaScript on the page. Continue reading to learn how you can improve your site’s user experience by safely checking if an object exists and preventing an error from occurring on the page.

Check if object exists in JavaScript

The safe way

if(typeof obj === 'undefined') {
    alert('object doesn't exist');
} else {
    alert('object exists');

The snippet above checks to see if an object exists and will display an alert message based off of the result. The method handles both of the events (existing and not existing) without generating any errors and that’s why it should be used when you check to see if an object exists.

The risky way

var obj = "test";
if(obj) {

The code above will “work”, however we’ll run into an issue if the variable obj is not defined. We’ll see an error message like the one shown below.


ReferenceError: obj is not defined

Because the method above generates an error when obj is not defined, we should should only use the first method so that we can provide clean code and a good user experience.