Table of Content
The forEach loop in JavaScript allows you to go through each item in an array. You do not have to write a full for loop or worry about indexes.
You give it a function, and it runs that function once for every item. This makes your code easier to read and cuts out the extra steps.
What is the forEach loop in JavaScript?
forEach is a method built into JavaScript arrays. It calls a provided function once for each element, in order. That does not change the original array.
The syntax:
array.forEach(function(currentValue, index, array) {
// your code here
});Parameters:
currentValue– the current element being processed.index– the index of the current element (optional).array– the full arrayforEachis being called on (optional).
Here is a quick example:
const fruits = ['apple', 'banana', 'cherry'];
fruits.forEach((fruit, index) => {
console.log(index + ': ' + fruit);
});The output:
0: apple
1: banana
2: cherry
It loops through the fruits array within forEach. It logs each fruit with its index in the format “index: fruit”.
Can you break or return in forEach?
You cannot use break or continue. Also, you can not stop a forEach loop early. The loop always runs through the full array.
If you try this:
const numbers = [1, 2, 3, 4, 5];
numbers.forEach((num) => {
if (num === 3) return; // This only skips to the next callback, not the loop
console.log(num);
});Output:
1
2
4
5
The return only exits the callback, not the loop itself. If you need to stop early, use a for, for...of, or some() loop instead.
Use Arrow Functions in forEach
Arrow functions let you write shorter functions in JavaScript. They don’t have their own this, so they fit well in forEach loops where you don’t need to set the context.
Here is a simple use:
const names = ['Liam', 'Emma', 'Noah'];
names.forEach(name => console.log('Hello, ' + name));Output:
Hello, Liam
Hello, Emma
Hello, Noah
This does the same as a full function but needs less code. Here are two examples that apply the forEach method with arrow functions:
Example 1: Update objects in an array:
const users = [
{ name: 'Alice', active: false },
{ name: 'Bob', active: false },
{ name: 'Carol', active: false }
];
users.forEach(user => user.active = true);
console.log(users);Output:
[
{ name: 'Alice', active: true },
{ name: 'Bob', active: true },
{ name: 'Carol', active: true }
]
Here is how it works:
- The array has objects with
nameandactivekeys. forEachgoes through each object.- The arrow function sets
activetotrue. - The array now holds updated objects.
Example 2: Build a lookup object:
Use forEach with an arrow function to turn an array into a key-value lookup:
const products = [
{ id: 101, name: 'Keyboard' },
{ id: 102, name: 'Mouse' },
{ id: 103, name: 'Monitor' }
];
const productMap = {};
products.forEach(product => {
productMap[product.id] = product.name;
});
console.log(productMap);Output:
{ '101': 'Keyboard', '102': 'Mouse', '103': 'Monitor' }
- The array holds product objects with
idandname. forEachadds each product toproductMap. It uses the product’s id as the key.- You now have a quick way to look up a product name by its ID.
Access Elements and Indexes within forEach
When you use forEach, JavaScript gives your callback function access to three things:
- The current element
- The index of that element
- The full array
You can use all three, or just the ones you need.
Example 1: Log each item with its index:
const colors = ['red', 'green', 'blue'];
colors.forEach((color, index) => {
console.log(index + ': ' + color);
});Output:
0: red
1: green
2: blue
coloris the current itemindexis its position in the array- You can combine them to show both
Example 2: Use all three arguments:
const items = ['pen', 'notebook', 'eraser'];
items.forEach((item, index, array) => {
console.log(item + ' is item ' + index + ' in [' + array.join(', ') + ']');
});Output:
pen is item 0 in [pen, notebook, eraser]
notebook is item 1 in [pen, notebook, eraser]
eraser is item 2 in [pen, notebook, eraser]
- The third argument gives you the full array
- This can help if you need to compare items or track something across the array
Nested Arrays within forEach loops
You can nest forEach loops when you want to work with arrays inside arrays. This happens with 2D arrays or arrays that hold objects with their own arrays.
The outer loop handles the main list. The inner loop works on each sub-list or nested array.
Loop through a 2D array:
const matrix = [
[1, 2],
[3, 4],
[5, 6]
];
matrix.forEach(row => {
row.forEach(num => {
console.log(num);
});
});Output:
1
2
3
4
5
6
- The outer
forEachgets each row (an inner array). - The inner
forEachloops through each number in the row. - This lets you go through every value in a 2D array.
Loop through objects with nested arrays:
const users = [
{ name: 'Anna', hobbies: ['read', 'cycle'] },
{ name: 'Ben', hobbies: ['game', 'cook'] }
];
users.forEach(user => {
console.log(user.name + "'s hobbies:");
user.hobbies.forEach(hobby => {
console.log('- ' + hobby);
});
});Output:
Anna's hobbies:
- read
- cycle
Ben's hobbies:
- game
- cook
- Each
userhas ahobbiesarray. - The outer loop goes through each user.
- The inner loop prints each hobby.
- This is useful when you work with nested data such as JSON responses.
Use async/await inside forEach
You can write async functions in JavaScript, but forEach does not wait for them to finish. This causes problems when you try to use await inside a forEach loop.
For example:
const fetchData = async (id) => {
// fake async action
return new Promise(resolve => {
setTimeout(() => resolve('Item ' + id), 1000);
});
};
const ids = [1, 2, 3];
ids.forEach(async id => {
const result = await fetchData(id);
console.log(result);
});
console.log('Done');Output: (Not in order)
Done
Item 1
Item 2
Item 3
- Each
asynccallback runs, butforEachdoes not wait. "Done"prints before theawaitcalls finish.- You lose control over the order with the time.
So, how to Fix It?
Use a for...of loop with await instead:
const fetchData = async (id) => {
return new Promise(resolve => {
setTimeout(() => resolve('Item ' + id), 1000);
});
};
const ids = [1, 2, 3];
const run = async () => {
for (const id of ids) {
const result = await fetchData(id);
console.log(result);
}
console.log('Done');
};
run();Correct Output:
Item 1
Item 2
Item 3
Done
for...ofworks withawaitas expected.- The loop waits for each fetch to finish.
- The output stays in order, and
"Done"prints last.
Loop over NodeList with forEach
When you use document.querySelectorAll() in JavaScript, it returns a NodeList. A NodeList looks like an array, and you can loop through it with forEach in most modern browsers.
For example:
<p>One</p>
<p>Two</p>
<p>Three</p>
<script>
const paragraphs = document.querySelectorAll('p');
paragraphs.forEach(p => {
p.textContent = 'Updated';
});
</script>querySelectorAll('p')returns aNodeListof all<p>elements.forEachloops through each node.- The arrow function updates the text for each
<p>.
Browser support:
forEachworks onNodeListin all modern browsers.- Older Internet Explorer versions do not support it.
- If you need full support you have to convert the
NodeListto an array:
Array.from(paragraphs).forEach(p => {
p.textContent = 'Updated';
});Or use the spread operator:
[...paragraphs].forEach(p => {
p.textContent = 'Updated';
});Here is another example to add a class to all matching elements:
const buttons = document.querySelectorAll('.btn');
buttons.forEach(button => {
button.classList.add('active');
});You can use forEach to update styles, add classes, or bind events to each element in the NodeList.
Wrapping Up
You now know how forEach works in JavaScript. It enables you to use a way to go through arrays and NodeLists.
Here is a quick recap:
forEachruns a function on each item in order. It doesn’t change the original array.- You can pass up to three arguments such as:
- Item,
- Index
- The array.
- You get the index and the array if you need them.
- You can nest
forEachto handle 2D arrays or complex data. - You can’t break out of it early.
breakandreturndon’t work. - It doesn’t wait for
await. Usefor...ofwhen you need to pause. - You can also use it with
querySelectorAll()to update DOM elements.
Thank you for reading. Click here to see more JavaScript tutorials.
FAQ’s
What is the forEach loop in JavaScript?
const fruits = ['apple', 'banana', 'cherry'];
fruits.forEach((fruit, index) => {
console.log(index + ': ' + fruit);
});
Can you break or return in a forEach loop?
const numbers = [1, 2, 3, 4, 5];
numbers.forEach((num) => {
if (num === 3) return; // This only exits the current function, not the loop
console.log(num);
});
How do arrow functions work with forEach?
const names = ['Liam', 'Emma', 'Noah'];
names.forEach(name => console.log('Hello, ' + name));
How can you access elements and indexes using forEach?
const colors = ['red', 'green', 'blue'];
colors.forEach((color, index, array) => {
console.log(${index}: ${color} in [${array.join(', ')}]);
});
Similar Reads
Math.asin() finds the arc sine of a number in JavaScript. It helps you work with angles from values. You get…
Mocha is a JavaScript test framework for Node.js. It runs tests in sequence and shows results. It works with any…
Arrow function gives you short code and keeps this in the right scope in JavaScript. Understand the Arrow Function in…
You will learn what the JavaScript valueOf function does and how it works. It returns the primitive value of an…
JavaScript has a statement called "with" that changes how code accesses object properties. The"with" Function makes a temporary scope, so…
You need to compare values in almost every JavaScript program. This is where comparison operators come in. They check if…
JavaScript Math.sqrt() solves the need to get square roots fast. Before it, you wrote custom code or used loops. It…
JavaScript optional chaining lets you access object values without runtime errors. It checks if a property exists before access and…
The JavaScript unshift function adds one or more elements at the start of an array. It shifts existing items to…
The assignment operator in JavaScript stores and updates values. It helps you hold data in a variable and change it…