JavaScript Array forEach() Method | jquery foreach each
Example1Callsafunctionforeachelementinfruits:constfruits=["apple","orange","cherry"];fruits.forEach(myFunction);TryitYourself»[1]DefinitionandUsageTheforEach()methodcallsafunctionforeachelementinanarray.TheforEach()methodisnotexecutedforemptyelements.Syntaxarray.forEach(function(currentValue,index,arr),thisValue)Parametersfunction()Required.Afunctiontorunforeacharrayelement.currentValueRequired.Thevalueofthecurrentelement.indexOptional.Theindexofthecurrentelement.arrOptional.Thearrayofthecur...
Example 1Calls a function for each element in fruits:
const fruits = ["apple", "orange", "cherry"];fruits.forEach(myFunction);
Try it Yourself »[1] Definition and UsageThe forEach() method calls a function for each element in an array.
The forEach() method is not executed for empty elements.
Syntaxarray.forEach(function(currentValue, index, arr), thisValue)
Parameters function() Required.A function to run for each array element. currentValue Required.The value of the current element. 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. Return Value More ExamplesCompute the sum:
let sum = 0; const numbers = [65, 44, 12, 4];numbers.forEach(myFunction);function myFunction(item) { sum += item;}
Try it Yourself »[2]Multiply each element:
const numb...