Javascript Array forEach()

Introduction

The forEach() method calls a function once for each array element.

arr.forEach(callback(currentValue [, index [, array]])[, thisArg])
Parameter
Optional
Meaning
callback




Not




Function to run on each element.
It takes three arguments:
currentValue - the current element.
index - Optional, the index of currentValue.
array - Optional, the whole array
thisArg
Optional
Value to use as this when executing callback.

forEach() does not change the array.

forEach() does not run on array holes.

Get the sum of all the values in the array:

var sum = 0;/*from   w  w  w. j a v a2s  . c om*/
var numbers = [65, 44, 12, 4];
numbers.forEach(myFunction);

function myFunction(item) {
  sum += item;
  console.log(sum);
}

For each element in the array: update the value with 10 times the original value:

var numbers = [65, 44, 12, 4];
numbers.forEach(myFunction)//from  w ww .j a  v a 2 s.c om

function myFunction(item, index, arr) {
  arr[index] = item * 10;
}

console.log(numbers);

More example

let languages = ['CSS', 'HTML', 'Java', 'SQL']
languages.forEach(function(item, index, array) {
   console.log(item, index)//from   w w  w.jav  a 2s.  c o m
});
const arraySparse = [1,3,,,,,7]/*ww w.  j av  a  2s. c o m*/
let numCallbackRuns = 0

arraySparse.forEach((element) => {
  console.log(element)
  numCallbackRuns++
})

console.log("numCallbackRuns: ", numCallbackRuns)

Converting a for loop to forEach

const items = ['item1', 'item2', 'item3']
const copy = []/*from   w  ww  .ja  va  2  s  . c om*/

for (let i = 0; i < items.length; i++) {
  copy.push(items[i])
}

items.forEach(function(item){
  copy.push(item)
})

Printing the contents of an array

index 2 is skipped, since there is no item at that position in the array.

function logArrayElements(element, index, array) {
  console.log('a[' + index + '] = ' + element)
}
[1, 2, , 4].forEach(logArrayElements)/* ww  w .j a  v a 2s  . c  om*/

Modifying the array during iteration

forEach() does not make a copy of the array before iterating.

let words = ['one', 'two', 'three', 'four']
words.forEach((word) => {//from  w  w  w.java  2  s  . c  o m
  console.log(word)
  if (word === 'two') {
    words.shift()
  }
});



PreviousNext

Related