DEV Community

john tanko
john tanko

Posted on

A Complete Guide to forEach in JavaScript: How to Iterate Arrays Like a Pro

Guide to forEach in JavaScript: How to Iterate Arrays Like a Pro
The most frequent task performed in a JavaScript environment is looping through arrays, for which one of the most widely used solutions was the forEach method. On surface level it's simple, but there are nuances that can truly impact how you efficiently use it.

The forEach array method can be tricky to understand if not used in the best manner possible and its applications. In this guide, we’ll walk through everything there is to the forEach method, from how to use it, to its best practices, to make you a forEach expert when it’s time to iterate through arrays!

What is forEach in JavaScript?

The forEach method is an array method that allows you to loop through elements in an array without using a traditional for loop.

Syntax:

array.forEach(function(element, index, array) {
// Your logic here
});

Parameters:

element – The current element being processed

index (optional) – The index of the current element

array (optional) – The original array being iterated

Basic Example:

const numbers = [1, 2, 3, 4, 5];

numbers.forEach(function(num) {
console.log(num * 2); // Output: 2, 4, 6, 8, 10
});

Why use forEach?
✔ Cleaner than traditional for loops
✔ No need for index tracking
✔ More readable code

When Should You Use forEach?

The best situations for forEach are: ✅ You only need to iterate over an array ✅ You don't have to return a new array (if you do, use.map() instead) ✅ You should refrain from managing loop counters by hand.

When NOT to Use forEach

❌ If you need to break or return early (use for...of or for loops instead)
❌ If you need performance optimization (loops can be faster)

Advanced forEach Techniques

1️⃣ Using Arrow Functions

For shorter, cleaner code, use arrow functions:

const names = ["Alice", "Bob", "Charlie"];
names.forEach(name => console.log(name.toUpperCase()));

2️⃣ Accessing Index Values

You can use the second parameter to access the index:

const fruits = ["🍎", "🍌", "🍇"];
fruits.forEach((fruit, index) => console.log(${index + 1}: ${fruit}));
// Output:
// 1: 🍎
// 2: 🍌
// 3: 🍇

3️⃣ Modifying Original Arrays (With Caution!)

forEach does not return a new array, but you can modify the original array:

let numbers = [1, 2, 3];
numbers.forEach((num, index, arr) => arr[index] = num * 10);
console.log(numbers); // [10, 20, 30]

✅ Useful when you need in-place updates
❌ Be careful—it mutates the array, which may cause unintended side effects.

4️⃣ Handling Asynchronous Code in forEach

forEach does NOT work well with async/await because it doesn't wait for async operations.

Incorrect Approach:

const fetchData = async (id) => {
let response = await fetch(https://api.example.com/data/${id});
let data = await response.json();
console.log(data);
};

[1, 2, 3].forEach(async (id) => {
await fetchData(id); // Won't wait for the fetch calls to complete
});

Correct Approach:
Use for...of instead for proper async handling:

const processArray = async () => {
for (const id of [1, 2, 3]) {
await fetchData(id);
}
};
processArray();

🆚 forEach vs Other Array Methods

forEach is often compared to other array methods like .map() and .concat(). If you need to concatenate multiple arrays, the array concat JavaScript method is a better choice:

const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const mergedArray = array1.concat(array2);
console.log(mergedArray); // [1, 2, 3, 4, 5, 6]

Similarly, if you need to concat string JavaScript, you can use:

const str1 = "Hello";
const str2 = "World";
const fullStr = str1.concat(" ", str2);
console.log(fullStr); // "Hello World"

Also, if you're wondering what is and in JavaScript, it's a bitwise operator that performs logical AND at a binary level.

console.log(5 & 1); // 1 (binary: 101 & 001)

Final Thoughts

forEach is a powerful tool when used correctly, but it’s important to know its limitations. It’s great for simple iteration but may not be the best choice for async operations or when you need to return a modified array.

Key Information:

✔ Use forEach for simple array iteration
✔ Don’t use it when you need break or return
✔ Consider .map(), for...of, .concat(), or .reduce() for other use cases

Try using forEach in your projects now that you understand how to use it! Do you have inquiries? Leave a comment below with them less share knowledge!

What is your preferred method for looping in JavaScript? Below, let's talk about it!

Playwright CLI Flags Tutorial

5 Playwright CLI Flags That Will Transform Your Testing Workflow

  • --last-failed: Zero in on just the tests that failed in your previous run
  • --only-changed: Test only the spec files you've modified in git
  • --repeat-each: Run tests multiple times to catch flaky behavior before it reaches production
  • --forbid-only: Prevent accidental test.only commits from breaking your CI pipeline
  • --ui --headed --workers 1: Debug visually with browser windows and sequential test execution

Learn how these powerful command-line options can save you time, strengthen your test suite, and streamline your Playwright testing experience. Practical examples included!

Watch Video 📹️

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please consider leaving a ❤️ or a kind comment on this post if it was useful to you!

Thanks!