Blog

Google Apps Script and JavaScript Arrays. Method .forEach()

Short description of the method

The .forEach() method, in essence, is a for loop, inside which the callback function sequentially processes all elements of the array.

The .forEach() method can pass three parameters to a callback function:

  1. the current value of the array element item
  2. optional parameter index - index of the current element
  3. optional and rarely used parameter array

This is perhaps the only method that returns nothing. Therefore, it is used for external processing, for example, for printing array elements.

const arr = [1, 2, 3, 4, 5];
  
  for (let i = 0; i < arr.length; i++) {
    console.log(arr[i]);
  };

// variant #1
  arr.forEach(function(item) {
    console.log(item);
  });

// variant #2
  arr.forEach(item => console.log(item));
  
  console.log('------------------------------------');
  
// callback function parameters
  arr.forEach((item, idx, array) => console.log(item, idx, array));

  console.log('------------------------------------');

// get intersection of arrays
  let arr1 = [1, 3, 5];
  let arr2 = [1, 2, 3, 4, 5];
  let result = [];

  let res = arr1.forEach(item => {
    if (arr2.includes(item)) return result.push(item);
  });

  console.log(result); // [ 1, 3, 5 ]
  console.log(res); // undefined

You can find more information in this video (RU voice):