Free: 4 trials of 20 minutes, no cardStart free

Craftstack Academy
Web

Uncaught TypeError: forEach is not a function, and how to fix it

· 8 min read

You want to colour every price on your page green. You select them, loop with forEach, and the console says:

Console
Uncaught TypeError: prices.forEach is not a function

TypeError: x.forEach is not a function means the value before .forEach isn't an array, or anything else that has a forEach method. You expected a list you can loop over, and you got something else: an HTMLCollection from getElementsByClassName, a plain object, a string, or JSON text that was never parsed. The fix depends on which one it is, and one line in the console tells you. This article covers the six usual cases.

Try it yourself

Save this as index.html, open it in your browser and look at the console (F12, then Console):

index.html
<!doctype html>
<html>
<body>
  <p class="price">10</p>
  <p class="price">20</p>
  <script>
    const prices = document.getElementsByClassName("price");
    prices.forEach(p => p.style.color = "green");
  </script>
</body>
</html>

You'll see the error above in Chrome or Edge. The two prices are found, there's no typo, and still forEach doesn't exist. Cause 1 explains why.

What the error means

Read it from the left:

  • TypeError: the value has the wrong type for what you did with it.
  • prices.forEach: the expression JavaScript tried to call. The part before .forEach, here prices, is the value to look at.
  • is not a function: that value has no method called forEach. Reading prices.forEach gave undefined, and you can't call undefined.

forEach is a method of arrays (and of a few other types: NodeList, Map and Set). So the question is: what is prices really, if it isn't an array? Find out by logging it:

js
console.log(Object.prototype.toString.call(prices));

In our test, this printed [object HTMLCollection] for getElementsByClassName and [object NodeList] for querySelectorAll. For a quick look, console.log(prices) and Array.isArray(prices) work too.

Cause 1: getElementsByClassName returns an HTMLCollection

document.getElementsByClassName and document.getElementsByTagName return an HTMLCollection. It looks like an array, has a length and works with [0], but it has no forEach.

Fix 1: use querySelectorAll

document.querySelectorAll returns a NodeList, which does have forEach:

js
document.querySelectorAll(".price").forEach(p => p.style.color = "green");

This is the simplest fix, and querySelectorAll is the more flexible method anyway: it takes any CSS selector. Remember the . for a class.

Fix 2: convert to a real array

Array.from turns any list-like value into a real array, with every array method:

js
Array.from(document.getElementsByClassName("price")).forEach(p => console.log(p.textContent));
Console
10
20

The spread syntax does the same: [...prices].forEach(...).

Fix 3: a for...of loop

for...of works on an HTMLCollection directly, without converting anything:

js
for (const p of document.getElementsByClassName("price")) {
  console.log("for-of", p.textContent);
}
Console
for-of 10
for-of 20

The same with map and filter

Note that a NodeList has forEach but not map, filter or reduce. On an HTMLCollection, map fails the same way:

Console
Uncaught TypeError: prices.map is not a function

For those, convert with Array.from first.

Cause 2: a plain object

Objects hold named values, and they don't have forEach:

js
const user = { name: "Sam", age: 31 };
user.forEach(v => console.log(v));
Console
Uncaught TypeError: user.forEach is not a function

Use Object.entries, Object.keys or Object.values, which return arrays:

js
Object.entries(user).forEach(([key, value]) => console.log(key, value));
Console
name Sam
age 31

Cause 3: data from an API that isn't the array itself

APIs often return an object that contains the array, alongside other information:

js
const response = { results: ["x", "y"], total: 2 };
response.forEach(r => console.log(r));
Console
Uncaught TypeError: response.forEach is not a function

Loop over the property that holds the array: response.results.forEach(...). When you're not sure of the shape of the data, log it first with console.log(response) and look for the square brackets.

The same can happen one level deeper, like res.data.forEach(...) when the array is really in res.data.items.

Cause 4: JSON text that was never parsed

Data from localStorage, a file or some APIs arrives as text. Text that looks like an array is still a string:

js
const data = '["a","b"]';
data.forEach(x => console.log(x));
Console
Uncaught TypeError: data.forEach is not a function

Parse it first with JSON.parse:

js
const items = JSON.parse(data);
items.forEach(x => console.log(x));
Console
a
b

With fetch, call await response.json() instead of response.text(). If JSON.parse itself fails with is not valid JSON, the text wasn't JSON at all: log it and look at the first characters.

Cause 5: a string

Strings have no forEach either:

js
const word = "hello";
word.forEach(c => console.log(c));
Console
Uncaught TypeError: word.forEach is not a function

To loop over the characters, use for (const c of word), or spread the string into an array: [...word].forEach(...).

Cause 6: a single value from reduce or a function

map and filter return arrays, so you can chain forEach after them. reduce returns whatever you reduce to, often a single number:

js
const nums = [1, 2, 3];
const total = nums.reduce((a, b) => a + b, 0);
total.forEach(n => console.log(n));
Console
Uncaught TypeError: total.forEach is not a function

total is 6, a number. The same happens with your own functions that return one item instead of a list. Check what the function returns.

When the value is undefined

If the value is undefined instead of a wrong type, the message is different:

js
let list;
list.forEach(x => x);
Console
Uncaught TypeError: Cannot read properties of undefined (reading 'forEach')

"Not a function" means the value exists but has no forEach. "Cannot read properties of undefined" means the value doesn't exist at all: a variable that was never set, or a property name with a typo. For the null version with elements, see Cannot read properties of null (reading 'addEventListener').

Map and Set have forEach too

Not everything with forEach is an array. Map and Set have their own, and they work as expected:

js
new Map([["a", 1]]).forEach((value, key) => console.log(key, value));
new Set([1]).forEach(v => console.log(v));
Console
a 1
1

Errors that look alike

  • x.map is not a function, x.filter is not a function: the same problem with other array methods.
  • Cannot set properties of null (setting 'innerHTML'): the element wasn't found at all. See Cannot set properties of null.
  • x is not defined: the variable doesn't exist in the code at all.

Wrong fixes that don't help

  • Adding .forEach to the HTMLCollection yourself. Changing built-in objects causes more problems than it solves.
  • Wrapping the value in an array: [prices].forEach(...). You'd loop once, over the whole collection, not over each price.
  • for...in on an array or collection. It loops over keys and can include extra properties. Use for...of.

A debugging walkthrough

items.forEach is not a function appears after you load data:

  1. Log the value right before the loop: console.log(items).
  2. Look at what's printed. Quotes around it? It's a string: parse it. Curly brackets? An object: find the array inside or use Object.entries. HTMLCollection? Use querySelectorAll or Array.from.
  3. Run Array.isArray(items). true means you're done here; the problem is elsewhere.
  4. Fix where the value comes from, not only at the loop: parse once, select with querySelectorAll, or pick the right property.

Practice

Which of these work?

  1. document.querySelectorAll("p").forEach(p => console.log(p))
  2. document.getElementsByTagName("p").forEach(p => console.log(p))
  3. Object.values({ a: 1, b: 2 }).forEach(v => console.log(v))

Answers. (1) Works: a NodeList has forEach. (2) forEach is not a function: getElementsByTagName returns an HTMLCollection. (3) Works: prints 1 and 2.

Frequently asked questions

Why is forEach not a function on getElementsByClassName?

It returns an HTMLCollection, which has no forEach. Use querySelectorAll(".name"), or Array.from(...) first.

What's the difference between HTMLCollection and NodeList?

Both are list-like. A NodeList from querySelectorAll has forEach; an HTMLCollection doesn't. Neither has map or filter.

How do I loop over an object in JavaScript?

Object.entries(obj).forEach(([key, value]) => ...), or Object.keys and Object.values.

How do I check if a value is an array?

Array.isArray(value) returns true or false.

Is "forEach is not a function" the same in Node.js?

Yes, the message is the same. In Node.js there's no document, so the cause is usually an object, a string or unparsed JSON.

A quick checklist

  1. Log the value before .forEach.
  2. From getElementsByClassName? Use querySelectorAll, or Array.from.
  3. An object? Use Object.entries, Object.keys or Object.values.
  4. A string that looks like an array? JSON.parse it.
  5. An API response? Loop over the property that holds the array.

For a method that works on any error, read how to read an error message. MDN documents Array.prototype.forEach and HTMLCollection.

1 beginner error a week

One common error, what it means and how to fix it, in a short email. Free, and you can unsubscribe in any email.

Learn by writing the code yourself.

Twenty minutes with the tutor, right in your browser. No card, nothing to install.

Start the free trial
A session: the tutor's chat on the left, the code editor with a Java program and its output on the right