Sammy
Sammy

Reputation: 43

Google Apps Script: strange "Missing ; before statement." error

I'm writing a simple script to scrap some reporting numbers. I'm getting the error message "Missing ; before statement.", which doesn't seem to be an accurate description of the issue at hand.

I've tried omitting pieces of the code but the error message seems fairly stochastic. I'm suspecting some issue with some of the classes I'm using, but I'm out of ideas.

Here is my code:

function getStats() {
  var stats = {'id': '',
               'impressions': 0,
               'clicks': 0,
               'conversions': 0,
               'cpa': 0,
               'cost': 0},
      campaignIterator = AdWordsApp.campaigns().get(),
      campaign,
      campaignstats;

  Logger.log('Fetching stats for last 7 days.');

  while (campaignIterator.hasNext()) {
    var campaign = campaignIterator.next();
    var campaignstats = campaign.getStatsFor('LAST_7_DAYS');
    var stats['impressions'] = stats['impressions'] + campaignstats.getImpressions();
    var stats['clicks'] = stats['clicks'] + campaignstats.getClicks();
    var stats['conversions'] = stats['conversions'] + campaignstats.getConversions();
    var stats['cost'] = stats['cost'] + campaignstats.getCost();
  }

  var stats['cpa'] = stats['cost']/stats['conversion'];
}

function main() {
  getStats();
}

Thanks for any help!

Upvotes: 4

Views: 11276

Answers (1)

nnnnnn
nnnnnn

Reputation: 150040

Remove the var statement from each line within the while loop, and from the statement after it.

Aside from the fact that all of those variables are already defined (though redeclaring the same variable doesn't cause an error), you've got syntax errors because you can't include square brackets in variable declarations like this:

var stats['impressions'] = ...

Try this:

while (campaignIterator.hasNext()) {
  campaign = campaignIterator.next();
  campaignstats = campaign.getStatsFor('LAST_7_DAYS');
  stats['impressions'] += campaignstats.getImpressions();
  stats['clicks'] += campaignstats.getClicks();
  stats['conversions'] += campaignstats.getConversions();
  stats['cost'] += campaignstats.getCost();
}

stats['cpa'] = stats['cost']/stats['conversion'];

Note also that I took the liberty of introducing the += operator. The following two statements are equivalent, but the latter is less to type and (arguably) easier to read:

x[y] = x[y] + z;
x[y] += z;

Upvotes: 4

Related Questions