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]; … }.
| Rhino | V8 |
|---|---|
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
for…in(withouteach) gives keys, not values. Swapping only the keyword silently changes behaviour.for eachovernulldid nothing in Rhino;for…of nullthrows. V8Shift writesObject.values(x || {})to keep the Rhino behaviour.- Array comprehensions and generator expressions using
for eachneed a.map()/.filter()rewrite.
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.