The forEach()
method calls a function for each element in an array in ascending index order. It is not invoked for index properties that have been deleted or are uninitialized.
The forEach()
method is not executed for empty elements.
The JavaScript forEach method is one of the several ways to loop through arrays.
In this tutorial, you will learn about JavaScript forEach() method with the help of examples.
Syntax
array.forEach(function(currentValue, index, arr), thisValue)
Parameters
function() | Required. Function to execute on each element. It accepts between one and three arguments. |
currentValue | Required. The current element being processed in the array. |
index | Optional. The index of the current element. |
arr | Optional. The array of the current element. |
thisValue | Optional. Default undefined .A value passed to the function as its this value. |
The return value of this method is always undefined.
Example
let students = ['John', 'Simran', 'Jack'];
// using forEach
students.forEach(myFunction);
function myFunction(item) {
console.log(item);
}
/*-OUTPUT-
John
Simran
Jack
*/
In the above program, the forEach()
method takes myFunction()
function that displays each element of a students array.
var array_1 = [2, 3, 4, 5, 6];
array_1.forEach(function(number, i) {
array_1[i] *= 2;
});
document.write(array_1);//4, 6, 8, 10, 12
let numbers = [1, 3, 4, 9, 8];
// function to compute square of each number
function computeSquare(element) {
console.log(element * element);
}
// compute square root of each element
numbers.forEach(computeSquare);
/* Output:
1
9
16
81
64
*/
Updating the Array Elements
let students = ['John', 'Simran', 'Jack'];
// using forEach
students.forEach(myFunction);
function myFunction(item, index, arr) {
// adding strings to the array elements
arr[index] = 'Hello ' + item;
}
console.log(students);
//["Hello John", "Hello Simran", "Hello Jack"]
forEach()
does not change the original array.
forEach()
executes callback
once for each array element in order.
forEach()
does not execute callback
for array elements without values.
Printing Contents of Array
function printElements(element, index) {
console.log('Array Element ' + index + ': ' + element);
}
const prices = [1800, 2000, 3000, , 5000, 500, 8000];
// forEach does not execute for elements without values
// in this case, it skips the third element as it is empty
prices.forEach(printElements);
/*Array Element 0: 1800
Array Element 1: 2000
Array Element 2: 3000
Array Element 4: 5000
Array Element 5: 500
Array Element 6: 8000*/
In this tutorial, you have learned how to use the JavaScript Array forEach()
method to execute a callback on every element of an array.