forEach Loop in JavaScript: A Complete Guide with Examples

JavaScript forEach Loop

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 array forEach is 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 name and active keys.
  • forEach goes through each object.
  • The arrow function sets active to true.
  • 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 id and name.
  • forEach adds each product to productMap. 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:

  1. The current element
  2. The index of that element
  3. 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
  • color is the current item
  • index is 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 forEach gets each row (an inner array).
  • The inner forEach loops 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 user has a hobbies array.
  • 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 async callback runs, but forEach does not wait.
  • "Done" prints before the await calls 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...of works with await as 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 a NodeList of all <p> elements.
  • forEach loops through each node.
  • The arrow function updates the text for each <p>.

Browser support:

  • forEach works on NodeList in all modern browsers.
  • Older Internet Explorer versions do not support it.
  • If you need full support you have to convert the NodeList to 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:

  • forEach runs 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 forEach to handle 2D arrays or complex data.
  • You can’t break out of it early. break and return don’t work.
  • It doesn’t wait for await. Use for...of when 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?

The forEach loop is a method available on JavaScript arrays that allows you to execute a provided function once for each array element. It shows the process of iterating over arrays without the need for a traditional for loop.
const fruits = ['apple', 'banana', 'cherry'];
fruits.forEach((fruit, index) => {
  console.log(index + ': ' + fruit);
});

Can you break or return in a forEach loop?

No, you cannot use break, continue, or return statements to exit a forEach loop early. The forEach method will execute the provided function once for each array element, and there is no way to stop or skip iterations using these statements. For example:
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?

Arrow functions provide a concise syntax for writing functions in JavaScript. When used with forEach, they make the code more readable and maintain the lexical scope of this.
const names = ['Liam', 'Emma', 'Noah'];
names.forEach(name => console.log('Hello, ' + name));

How can you access elements and indexes using forEach?

The forEach method provides access to the current element, its index, and the entire array through its callback function's parameters. for example:
const colors = ['red', 'green', 'blue'];
colors.forEach((color, index, array) => {
  console.log(${index}: ${color} in [${array.join(&#039;, &#039;)}]);
});
Previous Article

PHP File Inclusion: require, include, require_once, include_once

Next Article

JavaScript do while Loop: How it Works with Examples

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.