How to fix a Javascript Uncaught ReferenceError

Sometimes you may get an error that looks something like this:

Uncaught ReferenceError: <some_variable_or_function> is not defined

At first this can be quite the pain, but it usually just means that that variable, or function has either not been defined, or it isn’t ready for use yet.

It’s good practice to wrap this bit of code into a conditional check.

The original code

if (variable_or_function) {

The improved code

if (typeof variable_or_function !== 'undefined') {

Alternate methods

Does not execute if yourvar is undefined:

if (yourvar === null)

Any scope:

if (yourvar !== undefined)

Any scope: (my personal favourite)

if (typeof yourvar !== 'undefined')

With and without inheritance:

// with inheritance
if ('membername' in object)

// without inheritance
if (object.hasOwnProperty('membername'))

Check for truthy value:

if (yourvar)
Notify of
Inline Feedbacks
View all comments