Looping in Google Apps Script

Let's say you pass an array of values to be processed to a custom function, and you want to loop through them.  In these examples, we'll just go through each value and sum it if it is a number.

The traditional for loop

In this case, an index is used for each dimension of the values, using the .length property of the array to loop through the rows, then the columns, of the passed values.
 function sumStuff1 (values) {
 
   // traditional loop
   var sum = 0;
   for (var i=0; i < values.length ; i++ ) {
      for (var j=0; j < values[i].length ; j++) {
        if (typeof(values[i][j]) === 'number' ) { 
          sum += values[i][j];
        }
      }
   }
   return sum;
 }


forEach and the anonymous function

In later versions of javaScript, the forEach method was added to the Array object. The JavaScript engine used by Google Apps Script has this pattern available. 

This will call a function for each member of an array, passing the value found at each array element. We can write an anonymous function which .forEach will call to do something with each Array element. Since this is a two dimensional array, the outer forEach loop calls the function with a single dimension array representing a single row of values, and the inner loop calls a second anonymous function passing the value of the cell at each element of the row.

This anonymous function pattern is a fundamental one in javaScript, and although the syntax will at first seem unfamiliar to those coming from VBA, it is a powerful and common JavaScript construct.

  function sumStuff2 (values) {
 
   // anonymous function loop
   var sum = 0;
   values.forEach (function (row) {
     row.forEach ( function (cell) {
        if (typeof(cell) === 'number' ) { 
          sum += cell;
        }
     });
   }); 
   return sum;
 }

For more like this, see  From VBA to Google Apps Script . Why not join our forum,follow the blog or follow me on twitter to ensure you get updates when they are available. 

Transitioning is covered more comprehensively in my my book, Going Gas - from VBA to Apps script, available All formats are available now from O'Reilly,Amazon and all good bookshops. You can also read a preview on O'Reilly.






Comments