Topic 46 of 87
Array Iteration
Overview
While traditional for loops work perfectly fine, modern JavaScript favors declarative iteration methods. The most basic of these is .forEach().
.forEach() executes a provided callback function once for every element in the array. It is primarily used for performing "side effects" (like logging to the console or writing to a database) rather than transforming data.
Syntax
Using forEach
javascript
const numbers = [45, 4, 9];
// forEach passes 3 arguments to your callback:
// 1. The current item value
// 2. The current index
// 3. The entire array itself (rarely used)
numbers.forEach((val, index) => {
console.log(`Index ${index}: ${val}`);
});Common Pitfalls
- Trying to use
breakorcontinueinside aforEach. Because it is a callback function, standard loop control keywords cause Syntax Errors. If you need to break out early, use afor...ofloop instead. - Trying to return a value from a
forEach. The.forEach()method ALWAYS returnsundefined. If you want to create a new array based on the old one, you must use.map().
Interview Questions
Q:
Can you run asynchronous code (using await) sequentially inside a
.forEach()?A:
No. .forEach() is not promise-aware. It fires off all the callbacks concurrently and doesn't wait for the promises to resolve. To await sequentially, you must use a standard for...of loop.
Real-World Example
Logging every validation error from a form submission.
example
javascript
validationErrors.forEach(err => console.error(err.message));Check Your Knowledge
Test your understanding of Array Iteration with these quick questions.