Error guides

Fix "SyntaxError: Unexpected identifier 'each'" in Apps Script V8

SyntaxError: Unexpected identifier 'each'

You get this the moment a project switches from the Rhino runtime to V8 (or when Google force-migrates it). The whole file fails to load, so every function in it stops — triggers, menus, web apps.

Why it happens

for each (var x in obj) was a JavaScript 1.6 extension. Rhino accepted it and looped over values. It never became standard ECMAScript, and V8 rejects it at parse time.

The fix

Loop over values with for…of:

// Rhino
for each (var row in rows) {
  total += row[2];
}

// V8 — arrays
for (var row of rows) {
  total += row[2];
}

// V8 — plain objects (values)
for (var value of Object.values(obj)) {
  Logger.log(value);
}

Google's migration guide suggests the equivalent for (var key in obj) { var value = obj[key]; … }.

RhinoV8
for each (var v in array)for (const v of array)
for each (var v in object)for (const v of Object.values(object))
[x * 2 for each (x in a)] (array comprehension)a.map((x) => x * 2)
for each (var item in xml..item) (E4X)root.getDescendants() via XmlService — see the E4X guide

Gotchas

How V8Shift handles it

Every for each statement is rewritten automatically to for (… of Object.values(…)). Comprehensions are listed in the manual checklist with file and line.

Have a whole project to migrate? Paste your .gs or upload a zip for a free V8 compatibility report — every occurrence of this pattern with file and line, plus an auto-rewritten project.
Related errors