How to Use forEach in JavaScript: Syntax and Examples
In JavaScript,
forEach is a method used to run a function on each item in an array. You call array.forEach(callback), where callback is a function that receives each item, its index, and the array itself.Syntax
The forEach method calls a provided function once for each element in an array, in order.
- array: The array you want to loop through.
- callback: A function that runs on each element. It can take up to three arguments:
element: The current item in the array.index(optional): The position of the current item.array(optional): The original array.
javascript
array.forEach(function(element, index, array) { // code to run on each element });
Example
This example shows how to use forEach to print each fruit name with its position in the list.
javascript
const fruits = ['apple', 'banana', 'cherry']; fruits.forEach((fruit, index) => { console.log(`${index + 1}: ${fruit}`); });
Output
1: apple
2: banana
3: cherry
Common Pitfalls
One common mistake is trying to use forEach with return to stop the loop early, but forEach always runs on every element.
Also, forEach does not return a new array, so it is not suitable when you want to transform data.
javascript
const numbers = [1, 2, 3, 4]; // Wrong: trying to break out of forEach numbers.forEach(num => { if (num === 3) { return; // only exits current callback, not the loop } console.log(num); }); // Right: use a for loop to break early for (const num of numbers) { if (num === 3) break; console.log(num); }
Output
1
2
1
2
Quick Reference
- Use forEach to run code on each array item without creating a new array.
- Cannot break out of the loop early.
- Callback arguments: element, index, array.
- Does not return a value (returns undefined).
Key Takeaways
Use
forEach to execute a function on every item in an array.forEach callback receives element, index, and the whole array as arguments.You cannot stop or break a
forEach loop early; it always runs on all elements.forEach does not return a new array or any value.For transformations or early exit, use other methods like
map or a for loop.