Uncaught TypeError: 'undefined' is not a function
Reverse the order
For instance, while this code works as expected:
If you reverse the order of the statements the Uncaught TypeError: undefined is not a function error will occur:
So, It's better you double check that your scripts are being loaded correctly.
This weird behaviour depends on how you define the functions and when you call them.examples
This is because of something called hoisting!
- expression.that('returns').aFunctionObject(); // js
- execute -> expression.that('returns').aFunctionObject // what the JS engine does
That expression may be complex. So encountering the "undefined is not a function" error implies that the evaluated expression fails to yield a function object. Thus, it becomes crucial to discern that the element under execution is not a function. This situation warrants careful examination of the expression to pinpoint the discrepancy causing the error.
File order (library)
Occasionally, errors can arise due to inadequate or incorrect loading of libraries. In the context of libraries like jQuery, it's imperative to ensure the proper loading of the library before engaging in jQuery functions. This entails correctly incorporating the library into the webpage to facilitate the successful execution of desired jQuery operations. It should be something like:
- any third party plugins you loading
- your custom JS
This error manifests in Chrome when an attempt is made to call an undefined function. It can be validated by testing the scenario in the Chrome Developer Console and Mozilla Firefox Developer Console, where the error will become evident upon execution. Consider the following example:
When you execute the above code and then click on the page, an error surfaces: "Uncaught TypeError: this.myMessage is not a function." This error arises due to the anonymous function's execution context being bound to the document, while "myMessage" is defined on the window object. Consequently, the function cannot access "myMessage" as it resides in a different scope.
You can fix this issue by using the bind() method to pass the proper reference:
"Uncaught" signifies that the error wasn't captured within a try-catch block. The TypeError object denotes an error arising from a value that doesn't match the anticipated type. Additionally, "Undefined" pertains to a property within the global object. When a variable lacks an assigned value, it falls under the "undefined" type.