How to fix forEach is not a function Error in JavaScript
Table of Contents
When you work with JavaScript, you might come across this error:
BASHUncaught TypeError: X.forEach is not a function
This error occurs when you try to call the forEach
method on a variable that is not an array, map, or set.
In this post, we'll look at examples of how this error occurs and how to fix it.
How to fix TypeError: X.forEach is not a function
To start, lets look at some example code where this error occurs:
JAVASCRIPTconst elements = document.querySelectorAll(".element");
elements.forEach(element => console.log(element));
If you run this code, you will get:
BASHUncaught TypeError: elements.forEach is not a function
The reason for this is that elements
is not an array, but instead an array-like object, even though it looks like it should be just a normal array.
Instead, you will need to create an array from the elements by using Array.from
:
JAVASCRIPTconst elements = document.querySelectorAll(".element");
const array = Array.from(elements);
array.forEach(element => console.log(element));
If you want to check ahead of time if variable is an array and therefore has access to the forEach
function, simply use the Array.isArray
method:
JAVASCRIPTconst elements = document.querySelectorAll(".element");
if (Array.isArray(elements)) {
console.log("elements is an array");
} else {
console.log("elements is not an array");
}
BASHelements is not an array
Now you know when you can safely call forEach
or not.
Conclusion
In this post, we looked at examples of what causes the Uncaught TypeError: X.forEach is not a function
error.
Simply ensure that the variable you are calling forEach
on is a valid array.
Thanks for reading!
- How to Install Node on Windows, macOS and Linux
- Getting Started with Electron
- How to Set Up Cron Jobs in Linux
- How to deploy a .NET app using Docker
- How to deploy a Node app using Docker
- Learn how to use v-model with a custom Vue component
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Learn how to build a Slack Bot using Node.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with React
- Setting Up a Local Web Server using Node.js