"; } Output: index: 4 index: 9 index: 16 index: 25 [Try it Β»](#) * * * ## Definition and Usage The forEach() method is used to call each element of an array and pass the element to a callback function. **Note:** forEach() does not execute the callback function for an empty array. * * * ## Browser Support The numbers in the table indicate the first browser version that supports the method. | Method | | | | | | | --- | --- | --- | --- | --- | --- | | forEach() | Yes | 9.0 | 1.5 | Yes | Yes | * * * ## Syntax array.forEach(callbackFn(currentValue, index, arr), thisValue) ## Parameters | Parameter | Description | | --- | --- | | _callbackFn(currentValue, index, arr)_ | Required. The function to be called for each element in the array. Function parameters: | Parameter | Description | | --- | --- | | _currentValue_ | Required. The current element. | | _index_ | Optional. The index of the current element. | | _arr_ | Optional. The array object the current element belongs to. | | | _thisValue_ | Optional. The value to be passed to the function as the "this" value. If this parameter is empty, "undefined" will be passed as the "this" value. | Other forms of syntax: // Arrow function forEach((element)=>{/* β¦ */}) forEach((element, index)=>{/* β¦ */}) forEach((element, index, array)=>{/* β¦ */}) // Callback function forEach(callbackFn) forEach(callbackFn, thisArg) // Inline callback function forEach(function(element){/* β¦ */}) forEach(function(element, index){/* β¦ */}) forEach(function(element, index, array){/* β¦ */}) forEach(function(element, index, array){/* β¦ */}, thisArg) * * * ## Technical Details | Return Value: | undefined | | --- | | JavaScript Version: | ECMAScript 3 | ## More Examples ## Example Calculate the sum of all elements in an array:
Sum of array elements:
var sum = 0; var numbers = [65, 44, 12, 4]; function myFunction(item) { sum += item; demo.innerHTML = sum; } [Try it Β»](#) ## Example Multiply all values in an array by a specific number:Multiply by:
Calculated values:
var numbers = [65, 44, 12, 4]; function myFunction(item,index,arr) { arr = item * document.getElementById("multiplyWith").value; demo.innerHTML = numbers; } [Try it Β»](#) * * * ## forEach() with continue and break forEach() itself does not support the continue and break statements. We can achieve this using (#) and (#). Use the return statement to achieve the effect of the **continue** keyword: ### Implementing continue ## Example var arr =[1,2,3,4,5]; arr.forEach(function(item){ if(item ===3){ return; } console.log(item); }); !(#) var arr =[1,2,3,4,5]; arr.some(function(item){ if(item ===2){ return;// Cannot be return false } console.log(item); }); !(#) ### Implementing break ## Example var arr =[1,2,3,4,5]; arr.every(function(item){ console.log(item); return item !==3; }); !(#) * * JavaScript Array Object](#)
YouTip