Function Not Defined in JavaScript (How to Fix It)

ReferenceErrors are annoying. These common mistakes and clues to look for will help you get to the meat of it.

Published Categorized as JavaScript, Web & Code

You’re trying to call your JavaScript function. But, whenever you do, the result is a ReferenceError that goes like this:

// Call the function
myFunction();

// ReferenceError
Uncaught ReferenceError: myFunction is not defined

What went wrong? And how can you fix it?

Fear not; it happens to the best of us! The good news is that this ReferenceError is usually caused by one of the oversights that you and I will go through below. With a little investigation and debugging, you should be able to find the root cause in no time.

The Function Isn’t Defined at All

The most obvious—and, ironically, the most common—cause for the function not defined error is that, no prizes for guessing, the function isn’t defined in your code at all.

To save yourself hours of chasing a red herring, this is also the first probable cause you should rule out when debugging your code.

For those of you just getting started with JavaScript, here is a code snippet to illustrate what I mean:

// Define (or declare) the function
function saySomething(message) {
  console.log(message);
};

// Call the function
saySomething("The answer to life, the universe, and everything, is 42.");

Lines 2 through 4 define (or declare) our function. They consist of:

  • The function keyword
  • The name of the function, in our case saySomething
  • A list of the parameters it consumes (message)
  • The function’s statement between curly brackets {console.log(message)}

Only after we’ve defined our function properly can we call it with saySomething(), as shown on line 7.

The question is, what could be causing this?

Sanity-check #1:

If your function’s definition is supposed to be included within a <script> element in the HTML document, make sure that the script within the element (or the version of it that’s currently loaded in your app) actually contains it.

You might be testing against an older version of the document that doesn’t contain the function definition you need. Or you may be coming across caching issues, whether server- or client-side.

Sanity-check #2:

If your function’s definition is supposed to be included in an externally-hosted script, for example <script src="cdn.site.com/script.js"></script>, check if the URL of that script is correct, if the script is indeed there, and if the version of the script you need is what’s being returned by the CDN or server.

Once again, version control and/or caching are usually the culprits here. Identifying them early on can save you minutes, and sometimes hours, of dead-end debugging.

You’re Calling the Function Before It’s Defined

If the code that calls your JavaScript function precedes that function’s definition in your HTML document, you will come across the function is not defined error.

This is very, very important to check and rule out before you proceed to investigating other probable causes.

To build on the example above, suppose we’re developing a super-simple frontend for a web app using HTML5 and JavaScript.

It has two <script> elements: one that defines and function and one that calls it. However, we ordered them wrongly within our HTML markup; the call for the function precedes the definition of that function in our document:

<!doctype html>
<html lang="en-US">

<head>
  <meta charset="utf-8">
  <title>What's the answer to life?</title>
  <!-- Call function -->
  <script>
    populateAnswer("article.question-01 span.answer","The answer to life, the universe, and everything, is 42.");
  </script>
</head>

<body>
<article class="question-01">
<h1 class="question">Question: What's the answer to life?</h1>
<p>Answer: <span class="answer"></span></p>
</article>

<!-- Define function -->
<script>
  function populateAnswer(placeholder,answer) {
    document.querySelector(placeholder).innerHTML = answer;
  };
</script>
</body>

</html>

What’s happening here is that the browser, as it parses the HTML markup and interprets the JavaScript code, will try to call a function whose definition it hasn’t come across yet.

For this web app of ours to work, and to populate our <span class="answer"></span> element with the answer parameter, we need the function’s definition to come before the call:

<!doctype html>
<html lang="en-US">

<head>
  <meta charset="utf-8">
  <title>What's the answer to life?</title>
  <!-- Define function -->
  <script>
    function populateAnswer(placeholder,answer { document.querySelector(placeholder).innerHTML = answer; };
  </script>
  <!-- Call function -->
  <script>
    populateAnswer("article.question-01 span.answer","The answer to life, the universe, and everything, is 42.");
  </script>
</head>

<body>
<article class="question-01">
<h1 class="question">Question: What's the answer to life?</h1>
<p>Answer: <span class="answer"></span></p>
</article>
</body>

</html>

Sounds simple enough, doesn’t it?

Add a content management system like Drupal or WordPress to the mix and throw in a tag manager like Google Tag Manager or Adobe Launch, and it isn’t hard to see just how many things can go wrong by scripts being injected in the wrong sequence.

Sanity-check #1:

Where’s the <script> element that has your function’s definition? Pay special attention to scripts loaded in the <body>, whether at the start, in the middle, and especially down in the footer for performance reasons.

Are you trying to call the function before the definition? Remember that browsers have no memory for this, and will throw back a ReferenceError when it happens.

Sanity-check #2:

There’s a great deal of Google PageSpeed optimization tools out there nowadays, from Ezoic’s Leap for publishers to NitroPack for pretty much everyone else to all sorts of plugins, free and paid, for WordPress.

Almost all of these tools let you delay the execution of scripts until the DOM has finished loading. Although this improves your Google PageSpeed score, but can create issues for scripts that contain definitions of functions you’re calling within the DOM to write HTML elements directly into it.

Sanity-check #3:

Are you using a VPN? It’s not uncommon for CDNs and hosting providers to block the IPs of some of the most popular VPN apps out there, as they’re frequently used for attacks, fraud, and spam.

Disable your VPN and see if the problem persists. The JavaScript with the function’s definition might all of a sudden start loading. 🙂

Mistyped Name or Errors in Function

Burning the midnight oil to get the job done?

You’re more likely to make mistakes like mistyping your function’s name:

// Function definition
function myFunction(sayThis){ console.log(sayThis) };

// Mistyped name with lowercase letter
function myfunction("What's my name?");

// Mistyped name with typo
function myFuntion("What's my name?");

// Right name, no ReferenceError
function myFunction("That's my name!");

Sanity-check #1:

Check the name of your function. Is it spelled correctly? Now check if you’re calling that function with the right name, and whether you misspelled it in any way, including lowercase/uppercase characters.

Or omit parentheses in parameters, brackets in arrays, braces at the start and end of statements, and semi-colons wherever necessary:

// Forgot opening or closing parenthesis for the function's parameters
function myFunction(sayThis{console.log(sayThis) };

// Forgot opening or closing braces for the function's statement
function myFunction(sayThis){console.log(sayThis) ;

// Added extra brace at the start or end of the function's statement
function myFunction(sayThis){console.log(sayThis) }};

You can quickly uncover these oversights by checking for errors in your browser’s console. If you encounter an error message that says “myFunction is not a function” or that “this was expected instead of that,” you know you need to look closely at the code to see where you made a mistake.

Sanity-check #2:

Evaluate the browser’s console for errors. If you come across any related to your function, debug the function and fix whatever mistake(s) you made.

In Conclusion

Thank you for reading this far and I hope this helped.

Nine times out of ten, the biggest issues are caused by the smallest mistakes. (Which, since we’re human, we’re prone to making, especially when under time pressure and emotional stress.)

Whenever you come across a ReferenceError for your JavaScript function, check if it’s declared and, if the answer is “yes,” whether it’s declared and called in the right sequence. When you’ve ruled these out, chances are high that a mistyped name or error in the function are the root cause; investigate accordingly.

Image courtesy of alphaspirit /Depositphotos

Leave a comment

Your email address will not be published. Required fields are marked *