Iterators

Iterators are a common programming pattern used for traversing a list of objects when

  • The size of the list may not be known from the start.
  • Loading the entire list into memory at once may prove overly resource intensive.

Iterators expose two methods: boolean hasNext() and Object next(). AdWords scripts use the Iterator pattern for fetching AdWords entities.

Functionally, iterators are not too different from regular arrays, and may make your code more concise. Compare the code that traverses an array:

for (var i = 0; i < myArray.length; i++) {
  var myObject = myArray[i];
}
with code that traverses an iterator:
while (myIterator.hasNext()) {
  var myObject = myIterator.next();
}

The following code demonstrates the usage of an iterator over all campaigns in your account:

var campaignIterator = AdWordsApp.campaigns().get();

while (campaignIterator.hasNext()) {
  var campaign = campaignIterator.next();
  Logger.log(campaign.getName() +
      "; active? " + campaign.isEnabled() +
      "; budget=" + campaign.getBudget());
}

In AdWords scripts, entity iterators are often limited to fetching only the first 50,000 entities (see Limits for more information). However, it is possible to discover the total number of entities the iterator would have fetched by calling iterator.totalNumEntities(). This is useful when trying to split up work. For instance,

var keywords = campaign.keywords()
    .withCondition("Ctr > 0.01")
    .forDateRange("YESTERDAY")
    .get();
// Did we fetch more keywords than we can handle?
if (keywords.totalNumEntities() > 50000) {
    // Adjust the condition to fetch fewer keywords.
    keywords = campaign.keywords()
      .withCondition("Ctr > 0.015")
      .forDateRange("YESTERDAY")
      .get();
}

Application of withLimit() to a selector does not change the value of totalNumEntities(). x and y in the following snippet will have the same value:

var x = AdWordsApp.keywords().get().totalNumEntities();
var y = AdWordsApp.keywords().withLimit(5).get().totalNumEntities();

In order to obtain an Iterator of AdWords entities, one must construct a Selector first.

Send feedback about...

AdWords Scripts
AdWords Scripts
Need help? Visit our support page.