The forEach() method of the Array class in JavaScript calls a provided function once for each element in an array, in ascending order.
There are 2 variations for the syntax of Array.forEach() method. They are:
forEach(callbackFn)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
callbackFn | required | A function to execute on each element in the array. It takes three arguments: element, index, and array. |
This method calls a function for each element in the calling array.
Returns value of type undefined
.
forEach(callbackFn, thisArg)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
callbackFn | required | A function to execute on each element in the array. It takes three arguments: element, index, and array. |
thisArg | optional | A value to use as this when executing callbackFn. |
This method calls a function for each element in the calling array, using thisArg as the value of this inside callbackFn.
Returns value of type undefined
.
In JavaScript, we can use the forEach() method to log each element of an array to the console.
For example,
const arr = [1, 2, 3, 4, 5];
arr.forEach(element => console.log(element));
1 2 3 4 5
We can use the forEach() method to log each element and its index in an array to the console.
For example,
const arr = ['a', 'b', 'c'];
arr.forEach((element, index) => console.log(`Index: ${index}, Element: ${element}`));
Index: 0, Element: a Index: 1, Element: b Index: 2, Element: c
We can use the forEach() method with a thisArg to log each element of an array to the console using a specific context.
For example,
const arr = [1, 2, 3];
const context = { prefix: 'Number:' };
function logWithPrefix(element) {
console.log(`${this.prefix} ${element}`);
}
arr.forEach(logWithPrefix, context);
Number: 1 Number: 2 Number: 3
In this JavaScript tutorial, we learned about forEach() method of Array: the syntax and few working examples with output and detailed explanation for each example.