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) { //console.log(variable_or_function); }
Code language: JavaScript (javascript)

The improved code

if (typeof variable_or_function !== 'undefined') { //console.log(variable_or_function); }
Code language: JavaScript (javascript)

Alternate methods

Does not execute if yourvar is undefined:

if (yourvar === null)
Code language: JavaScript (javascript)

Any scope:

if (yourvar !== undefined)
Code language: JavaScript (javascript)

Any scope: (my personal favourite)

if (typeof yourvar !== 'undefined')
Code language: JavaScript (javascript)

With and without inheritance:

// with inheritance if ('membername' in object) // without inheritance if (object.hasOwnProperty('membername'))
Code language: JavaScript (javascript)

Check for truthy value:

if (yourvar)
Code language: JavaScript (javascript)
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments