How to fix a Javascript Uncaught ReferenceError

0 min read 130 words

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);
}

The improved code

if (typeof variable_or_function !== 'undefined') {
    //console.log(variable_or_function);
}

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)
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags