JavaScript – Iterate over Array using forEach()
JavaScript Array forEach() is used to run a callback function once for each element in an array. It is useful when you want to perform an action for every array item, such as printing values, building HTML output, updating totals, or calling another function for each element.
In this tutorial, we shall learn the syntax and usage of forEach() with examples. We will also cover the callback parameters, how to access the index, how thisArg works, what forEach() returns, and when another array method such as map(), filter(), or for...of may be a better choice.
How JavaScript Array forEach() works
The forEach() method belongs to JavaScript arrays. It takes a callback function and calls that callback for each existing element in the array, in ascending index order. The method is mainly used for side effects, such as logging, updating a variable, changing the DOM, or processing each item without creating a new array.
forEach() does not return a new array. Its return value is always undefined. If you need to transform every element and collect the transformed values, use map() instead.
JavaScript forEach() syntax for array iteration
The syntax of forEach() function is
arr.forEach(function callbackFun(currentValue[, index[, array]]) {
//set of statements
}[, thisArg]);
The callback function can receive up to three arguments. You may use only the arguments needed in your code.
Iterate over a JavaScript array using forEach()
In the following example, we take an array, and iterate over the elements using forEach() method.
index.html
<!doctype html>
<html>
<body>
<h1>JavaScript - forEach Example</h1>
<p id="message"></p>
<script>
<!-- your JavaScript goes here -->
var msg='';
var names = ['Arjun', 'Akhil', 'Varma'];
names.forEach(function printing(element, index, names){
msg += index + ' : ' + element + '<br>';
});
document.getElementById("message").innerHTML = msg;
</script>
</body>
</html>
The callback receives each name as element and its position as index. The example builds a string and writes it into the paragraph with the id message.
Use forEach() with an arrow function in JavaScript
Modern JavaScript code often uses an arrow function with forEach(). This keeps the callback shorter when the logic is simple.
const numbers = [10, 20, 30];
numbers.forEach((number) => {
console.log(number);
});
The callback runs once for each array element.
10
20
30
Get index while looping through an array with forEach()
The second callback argument gives the index of the current element. This is helpful when you need to display serial numbers, compare adjacent elements, or build labels using both the position and the value.
const fruits = ['Apple', 'Banana', 'Mango'];
fruits.forEach((fruit, index) => {
console.log(`${index}: ${fruit}`);
});
0: Apple
1: Banana
2: Mango
Use the original array parameter inside forEach()
The third callback argument refers to the array on which forEach() is running. It is not required in most programs, but it can be useful when the callback needs to compare the current element with values from the same array.
const marks = [80, 75, 90];
marks.forEach((mark, index, array) => {
const totalSubjects = array.length;
console.log(`Subject ${index + 1} of ${totalSubjects}: ${mark}`);
});
Subject 1 of 3: 80
Subject 2 of 3: 75
Subject 3 of 3: 90
Calculate a total using JavaScript forEach()
A common use of forEach() is to run an action for each number in an array. In the following example, the callback adds each value to an external variable named total.
const prices = [120, 80, 50];
let total = 0;
prices.forEach((price) => {
total += price;
});
console.log(total);
250
For numeric aggregation, reduce() is also a good option. Use forEach() when the step-by-step action is clearer for the reader or when you are doing side effects.
Use thisArg with JavaScript Array forEach()
The optional thisArg value sets the value of this inside a regular callback function. It does not work the same way with arrow functions because arrow functions do not have their own this.
const multiplier = {
factor: 3
};
const values = [2, 4, 6];
values.forEach(function (value) {
console.log(value * this.factor);
}, multiplier);
6
12
18
Important behavior of JavaScript forEach()
Before using forEach() in production code, remember these behavior rules:
forEach()calls the callback once for each existing array element.forEach()returnsundefined; it does not return a transformed array.- You cannot stop a
forEach()loop early usingbreakorcontinue. - Empty slots in sparse arrays are skipped.
awaitinside aforEach()callback does not make the outer loop wait in the way many beginners expect.
Why break and continue do not work inside forEach()
forEach() is a method call, not a loop statement. Because of that, break and continue cannot be used inside its callback. If you need early exit, use a for loop, for...of, some(), or every(), depending on the requirement.
const numbers = [1, 2, 3, 4, 5];
for (const number of numbers) {
if (number === 3) {
break;
}
console.log(number);
}
1
2
forEach() vs map() when iterating over JavaScript arrays
Use forEach() when you want to perform an action for each element and do not need a returned array. Use map() when you want to create a new array by transforming each element.
| Requirement | Better choice | Reason |
|---|---|---|
| Print each item | forEach() | The goal is a side effect. |
| Add each value to an existing total | forEach() or reduce() | forEach() is simple; reduce() is more functional. |
| Create a new array of doubled numbers | map() | map() returns a new array. |
| Stop when a condition is met | for...of, some(), or every() | forEach() has no normal early break. |
| Run asynchronous steps one after another | for...of with await | It is easier to control async flow. |
Common mistakes with JavaScript Array forEach()
- Expecting a returned array:
forEach()returnsundefined, so do not assign its result when you need transformed values. - Trying to use break:
breakis invalid inside aforEach()callback. Use a different loop when early exit is required. - Using async callbacks without control:
forEach()does not wait for promises in a sequential way. Usefor...ofwithawaitfor ordered asynchronous processing. - Changing the array without care: Mutating the same array while iterating can make code harder to understand. Prefer creating a new array when the goal is transformation.
Editorial QA checklist for this JavaScript forEach() tutorial
- The tutorial explains that
forEach()executes a callback for each existing array element. - The syntax section includes
currentValue,index,array, andthisArg. - The examples show both regular callback syntax and arrow function syntax.
- The page states that
forEach()returnsundefinedand should not be used when a transformed array is needed. - The article warns that
breakandcontinueare not used insideforEach()callbacks. - The comparison with
map(),reduce(), andfor...ofhelps readers choose the correct loop style.
JavaScript forEach() FAQs
What does forEach() do in JavaScript?
forEach() runs a callback function once for each existing element in an array. It is usually used when you want to perform an action for every item, such as printing values, updating the DOM, or accumulating a result.
Does JavaScript forEach() return a new array?
No. forEach() always returns undefined. Use map() if you want to create a new array from existing array values.
How do I get the index in JavaScript forEach()?
Use the second callback parameter to get the index. For example, array.forEach((value, index) => { ... }) gives both the current value and its index.
Can I break out of a JavaScript forEach() loop?
No. You cannot use break to exit a forEach() callback early. Use for, for...of, some(), or every() when early exit is required.
Should I use forEach() or for…of for asynchronous JavaScript code?
For sequential asynchronous code, prefer for...of with await. A forEach() callback can be marked async, but the outer forEach() call does not wait for each promise in a simple sequential manner.
Conclusion – iterating arrays with JavaScript forEach()
In this JavaScript Tutorial, we have learnt to use Array.forEach() method to apply a function for each element of the array. Use forEach() when the purpose is to perform an action for each item. Use map() for transformed arrays, reduce() for accumulated values, and for...of when you need early exit or clear asynchronous control.
TutorialKart.com