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