πŸ”§ Error Fixes
Β· 1 min read

TypeError: .forEach Is Not a Function β€” How to Fix It


TypeError: data.forEach is not a function

You’re calling .forEach() on something that isn’t an array.

Fix 1: It’s an object, not an array

const data = { a: 1, b: 2 };

// ❌ Objects don't have forEach
data.forEach(...)  // TypeError!

// βœ… Use Object.entries, Object.keys, or Object.values
Object.entries(data).forEach(([key, value]) => {
  console.log(key, value);
});

Fix 2: It’s a NodeList, not an array

const items = document.querySelectorAll('.item');

// βœ… NodeList has forEach in modern browsers
items.forEach(item => ...);

// βœ… Convert to array for older browsers
Array.from(items).forEach(item => ...);
[...items].forEach(item => ...);

Fix 3: The data is null or undefined

// ❌ API returned null
const data = null;
data.forEach(...)  // TypeError!

// βœ… Default to empty array
(data || []).forEach(item => ...);

Fix 4: It’s a string

const text = 'hello';

// ❌ Strings don't have forEach
text.forEach(...)  // TypeError!

// βœ… Use split or spread
[...text].forEach(char => console.log(char));

Related: Maximum Call Stack Size Exceeded β€” How to Fix It