Javascript functions not defined

Why is my JavaScript function sometimes «not defined»?

I call my JavaScript function. Why do I sometimes get the error ‘myFunction is not defined’ when it is defined? For example. I’ll occasionally get ‘copyArray is not defined’ even in this example:

function copyArray( pa ) < var la = []; for (var i=0; i < pa.length; i++) la.push( pa[i] ); return la; >Function.prototype.bind = function( po ) < var __method = this; var __args = []; // Sometimes errors -- in practice I inline the function as a workaround. __args = copyArray( arguments ); return function() < /* bind logic omitted for brevity */ >> 

As you can see, copyArray is defined right there, so this can’t be about the order in which script files load. I’ve been getting this in situations that are harder to work around, where the calling function is located in another file that should be loaded after the called function. But this was the simplest case I could present, and appears to be the same problem. It doesn’t happen 100% of the time, so I do suspect some kind of load-timing-related problem. But I have no idea what. @Hojou: That’s part of the problem. The function in which I’m now getting this error is itself my addLoadEvent, which is basically a standard version of the common library function. @James: I understand that, and there is no syntax error in the function. When that is the case, the syntax error is reported as well. In this case, I am getting only the ‘not defined’ error. @David: The script in this case resides in an external file that is referenced using the normal method in the page’s head section. @Douglas: Interesting idea, but if this were the case, how could we ever call a user-defined function with confidence? In any event, I tried this and it didn’t work. @sk: This technique has been tested across browsers and is basically copied from the Prototype library.

Читайте также:  Ide for php windows

Источник

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.

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

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 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 , 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 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>  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> 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 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>  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 element that has your function’s definition? Pay special attention to scripts loaded in the , 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(sayThisconsole.log(sayThis) >; // Forgot opening or closing braces for the function's statement function myFunction(sayThis)log(sayThis) ; // Added extra brace at the start or end of the function's statement function myFunction(sayThis)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.

Источник

JavaScript Function Not Defined Error (BUT IT IS DEFINED)

I have a JavaScript function which fires on blur. Strangely enough it worked fine the first time I ran it, and ever since then I’ve been getting an error that says JavaScript Function Not Defined — and it stops running. I have googled around similar problems but none of the advice has been able to resolve the issue. Asp.Net 3.5 Webforms, if it matters. I have included some extra functions and lines of code which may be unrelated to the problem. The issue I’m having regards updateFiscalGrid, the large function. The HTML which binds to the event is below the function.

    

Источник

Оцените статью