Introduction
JavaScript throws a TypeError: undefined is not a function
when you invoke something that isn’t callable. This error often appears in browser console or Node.js logs and blocks your code execution. Understanding common patterns makes it easy to resolve.
What Is the Error?
TypeError: undefined is not a function
at myFunction (app.js:10)
at HTMLButtonElement.onclick (index.html:5)
It means the identifier you’re calling evaluates to undefined
, not to a function reference.
Common Causes
- Typo in function or method name.
- Script or module load order: code runs before definition.
- Incorrect export/import in ES modules or CommonJS.
- Overwriting built-in methods or globals.
this
binding issues when using callbacks.
Solution 1: Check for Typos
Ensure the function name matches exactly:
// Wrong
element.addEventListerner('click', handleClick);
// Right
element.addEventListener('click', handleClick);
Solution 2: Verify Load Order
Load scripts in correct sequence:
<!-- library defines $.ajax -->
<script src="jquery.js"></script>
<script src="app.js"></script>
Or wrap calls in DOMContentLoaded
:
document.addEventListener('DOMContentLoaded', () => {
initApp();
});
Solution 3: Validate Imports and Exports
ES Modules:
// utils.js
export function doThing() { … }
// app.js
import { doThing } from './utils.js';
doThing();
CommonJS:
// utils.js
module.exports = { doThing };
// app.js
const { doThing } = require('./utils');
doThing();
Solution 4: Avoid Overwriting Globals
Don’t reuse names of standard APIs:
// BAD: overwrites window.fetch
const fetch = null;
fetch('/api'); // TypeError
Solution 5: Fix this
Binding
Use .bind()
or arrow functions to preserve context:
class MyClass {
constructor() {
this.method = this.method.bind(this);
}
method() { … }
}
Or:
button.addEventListener('click', () => this.method());
Conclusion
“TypeError: undefined is not a function” is usually a simple fix—correct names, load scripts in order, use proper imports, and ensure correct context. Following these guidelines prevents the error and keeps your JavaScript running smoothly.
Leave a comment