TypeError: undefined is not a function
TypeError: x.map is not a function
TypeError: x.forEach is not a function
Youβre trying to call something as a function, but itβs undefined, null, or not the type you think it is.
Fix 1: Typo in Method Name
// β Misspelled method
const items = [1, 2, 3];
items.forEeach(x => console.log(x)); // π₯ forEeach
// β
Correct spelling
items.forEach(x => console.log(x));
Fix 2: Calling a Method on the Wrong Type
// β .map() on an object (not an array)
const data = { name: "Alice" };
data.map(x => x); // π₯ Not an array
// β
Check the type first
if (Array.isArray(data)) {
data.map(x => x);
}
// Or convert to array
Object.values(data).map(x => x);
Fix 3: Variable Is Undefined
// β Function not imported or defined
processData(items); // π₯ processData is undefined
// β
Check your imports
import { processData } from './utils';
Fix 4: Wrong Export/Import
// β Default vs named export mismatch
// utils.js exports: export function helper() {}
import helper from './utils'; // π₯ undefined (it's a named export)
// β
Use named import
import { helper } from './utils';
Fix 5: Async Data Not Loaded Yet
// β Data is undefined until the API responds
const [users, setUsers] = useState();
users.map(u => u.name); // π₯ users is undefined on first render
// β
Default to empty array
const [users, setUsers] = useState([]);
// Or guard
users?.map(u => u.name);
Fix 6: Callback Not Passed
// β Calling a callback that wasn't provided
function fetchData(url, callback) {
const data = fetch(url);
callback(data); // π₯ If no callback passed
}
// β
Check if callback exists
if (typeof callback === 'function') {
callback(data);
}
Related resources
- TypeError: is not a function fix
- TypeError: Cannot read properties of undefined fix
- Cannot find module fix
Related: JavaScript Array Methods Cheat Sheet