forEach() Function

In Google Apps Script, the forEach() method is an array method that calls a provided function once for each element in an array, in order. The method takes a callback function as an argument, which is called for each element in the array. The callback function can take up to three arguments: the value of the element, the index of the element, and the array itself.

Sure, here is an example of using the forEach() method with a countries array:

var countries = ["USA", "Canada", "Mexico", "Brazil", "Argentina"];

// Log each country in the countries array
countries.forEach(function(country) {
  Logger.log(country);
});

In this example, we call the forEach() method on the countries array and pass a callback function that logs each country to the console. The method iterates over each element in the array and calls the callback function for each element. The output in the console will show each country in the countries array, one at a time.

You can also use the forEach() method to perform an operation on each element in an array:

var numbers = [1, 2, 3, 4, 5];

// Multiply each element in the numbers array by 2
numbers.forEach(function(num, index, arr) {
  arr[index] = num * 2;
});

// Output the new array
Logger.log(numbers); // Outputs: [2, 4, 6, 8, 10]

In this example, we call the forEach() method on the numbers array and pass a callback function that multiplies each element by 2. The method iterates over each element in the array and calls the callback function for each element, passing the value of the element, the index of the element, and the array itself as arguments. The callback function multiplies the value of the element by 2 and assigns the result back to the same index in the array. The new array is outputted to the log using the Logger.log() method.