How to simulate for each loop in javaScript

What can you learn here ?
  • javaScript class
  • enumeration
  • forEach method

Enumerating through a javaScript collection

In VBA, it is very useful to be able to enumerate through a collection of objects. In javaScript, there are no collections, everything is a quasi object and there are is no forEach concept.

for in

JavaScript does have this, and a bunch of great advanced array loops

for (key in object) {
 do something with key (the property name), object[key] (its value)

which would iterate through every property of object and return its name, but that's not the same thing as the VBA forEach.


To illustrate this, we are going to use a javaScript implementation of a VBA collection. Let's say that we have a collection as follows, and we then add things to it.
var co = new collection();

Typically, in VBA we would use
for each x in co
    do something with x
next x

Since neither the collection object, nor the for.each construct exist in javaScript, we have to simulate this as a method of the collection class, so it can be called as per the following pattern.
    function (x) {
        do something with x

What's happening here ?

First, in the collection class, I have implemented a method called forEach()
  this.forEach = function(yourFunction) {
    for (var i = 0 ; i < self.count() ; i++ ) {
     yourFunction( self.item(i+pBase), i+pBase) ; 

In javaScript, we can create an anonymous function  function (cItem,cIndex) {...} and pass it as an argument to forEach(). The forEach() method then calls back this anonymous function for every item in the collection, passing a couple of arguments, one of which is the current item in the collection as we pass through it. You then simply process the item as you would have done inside the VBA forEach loop.


Creating a forEach() method is an excellent way to abstract the structure of some list or collection of objects from your code, and once you have the pattern is no more complicated than in VBA. Take a look at VBA collection in javaScript, Apps Script timer collection or Optimizing access to sheet values to see practical implementations of this.  In the meantime why not join our forum,follow the blog or follow me on twitter to ensure you get updates when they are available.

Learning Apps Script, (and transitioning from VBA) are covered 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

If you prefer Video style learning I also have two courses available. also published by O'Reilly.
Google Apps Script for Developers and Google Apps Script for Beginners.