For-each loop in google apps script

phlaxyr picture phlaxyr · Oct 11, 2017 · Viewed 46.9k times · Source

How do you create a for-each loop in Google Apps Script?

I'm writing an email script with GAS, and I'd like to iterate through an array using a for-each loop, rather than a regular for-loop.
I've already seen this answer, but the object is undefined, presumably because the for loop doesn't work.

// threads is a GmailThread[]
for (var thread in threads) {
  var msgs = thread.getMessages();
  //msgs is a GmailMessage[]
  for (var msg in msgs) {
    msg.somemethod(); //somemethod is undefined, because msg is undefined.
  }
}


(I'm still new to javascript, but I know of a for-each loop from java.)

Answer

Branden Huggins picture Branden Huggins · Oct 17, 2017

Update: See @BBau answer below https://stackoverflow.com/a/60785941/5648223 for update on Migrating scripts to the V8 runtime.

In Google Apps Script:
When using "for (var item in itemArray)",
'item' will be the indices of itemArray throughout the loop (0, 1, 2, 3, ...).

When using "for each (var item in itemArray)",
'item' will be the values of itemArray throughout the loop ('item0', 
'item1', 'item2', 'item3', ...).

Example:

function myFunction() {
  var arrayInfo = [];
  
  arrayInfo.push('apple');
  arrayInfo.push('orange');
  arrayInfo.push('grapefruit');
  
  Logger.log('Printing array info using for loop.');
  for (var index in arrayInfo)
  {
    Logger.log(index);
  }
  Logger.log('Printing array info using for each loop.');
  for each (var info in arrayInfo)
  {
    Logger.log(info);
  }
}

Result:


    [17-10-16 23:34:47:724 EDT] Printing array info using for loop.
    [17-10-16 23:34:47:725 EDT] 0
    [17-10-16 23:34:47:725 EDT] 1
    [17-10-16 23:34:47:726 EDT] 2
    [17-10-16 23:34:47:726 EDT] Printing array info using for each loop.
    [17-10-16 23:34:47:727 EDT] apple
    [17-10-16 23:34:47:728 EDT] orange
    [17-10-16 23:34:47:728 EDT] grapefruit