You want to colour every price on your page green. You select them, loop with forEach, and the console says:
Uncaught TypeError: prices.forEach is not a functionTypeError: 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):
<!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, hereprices, is the value to look at.is not a function: that value has no method calledforEach. Readingprices.forEachgaveundefined, and you can't callundefined.
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:
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:
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:
Array.from(document.getElementsByClassName("price")).forEach(p => console.log(p.textContent));10
20The spread syntax does the same: [...prices].forEach(...).
Fix 3: a for...of loop
for...of works on an HTMLCollection directly, without converting anything:
for (const p of document.getElementsByClassName("price")) {
console.log("for-of", p.textContent);
}for-of 10
for-of 20The 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:
Uncaught TypeError: prices.map is not a functionFor those, convert with Array.from first.
Cause 2: a plain object
Objects hold named values, and they don't have forEach:
const user = { name: "Sam", age: 31 };
user.forEach(v => console.log(v));Uncaught TypeError: user.forEach is not a functionUse Object.entries, Object.keys or Object.values, which return arrays:
Object.entries(user).forEach(([key, value]) => console.log(key, value));name Sam
age 31Cause 3: data from an API that isn't the array itself
APIs often return an object that contains the array, alongside other information:
const response = { results: ["x", "y"], total: 2 };
response.forEach(r => console.log(r));Uncaught TypeError: response.forEach is not a functionLoop 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:
const data = '["a","b"]';
data.forEach(x => console.log(x));Uncaught TypeError: data.forEach is not a functionParse it first with JSON.parse:
const items = JSON.parse(data);
items.forEach(x => console.log(x));a
bWith 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:
const word = "hello";
word.forEach(c => console.log(c));Uncaught TypeError: word.forEach is not a functionTo 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:
const nums = [1, 2, 3];
const total = nums.reduce((a, b) => a + b, 0);
total.forEach(n => console.log(n));Uncaught TypeError: total.forEach is not a functiontotal 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:
let list;
list.forEach(x => x);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:
new Map([["a", 1]]).forEach((value, key) => console.log(key, value));
new Set([1]).forEach(v => console.log(v));a 1
1Errors 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
.forEachto 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...inon an array or collection. It loops over keys and can include extra properties. Usefor...of.
A debugging walkthrough
items.forEach is not a function appears after you load data:
- Log the value right before the loop:
console.log(items). - 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? UsequerySelectorAllorArray.from. - Run
Array.isArray(items).truemeans you're done here; the problem is elsewhere. - 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?
document.querySelectorAll("p").forEach(p => console.log(p))document.getElementsByTagName("p").forEach(p => console.log(p))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
- Log the value before
.forEach. - From
getElementsByClassName? UsequerySelectorAll, orArray.from. - An object? Use
Object.entries,Object.keysorObject.values. - A string that looks like an array?
JSON.parseit. - 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.
