πŸ”§ Error Fixes
Β· 1 min read

TypeError: undefined is not a function β€” How to Fix It


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: JavaScript Array Methods Cheat Sheet