🔧 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);
}