SyntaxError: for-in loop head declarations may not have initializers
The JavaScriptstrict mode-only exception"for-in loop head declarations may not have initializers"occurs when the head of afor...in containsan initializer expression, such asfor (var i = 0 in obj)
. This is notallowed in for-in loops in strict mode. In addition, lexical declarations with initializers likefor (const i = 0 in obj)
are not allowed outside strict mode either.
Message
SyntaxError: for-in loop variable declaration may not have an initializer. (V8-based)SyntaxError: for-in loop head declarations may not have initializers (Firefox)SyntaxError: a lexical declaration in the head of a for-in loop can't have an initializer (Firefox)SyntaxError: Cannot assign to the loop variable inside a for-in loop header. (Safari)
Error type
What went wrong?
The head of afor...in loop contains an initializer expression.That is, a variable is declared and assigned a valuefor (var i = 0 in obj)
.In non-strict mode, this head declaration is silently ignored and behaves likefor (var i in obj)
.Instrict mode, however, aSyntaxError
is thrown. In addition, lexical declarations with initializers likefor (const i = 0 in obj)
are not allowed outside strict mode either, and will always produce aSyntaxError
.
Examples
This example throws aSyntaxError
:
const obj = { a: 1, b: 2, c: 3 };for (const i = 0 in obj) { console.log(obj[i]);}// SyntaxError: for-in loop head declarations may not have initializers
Valid for-in loop
You can remove the initializer (i = 0
) in the head of the for-in loop.
const obj = { a: 1, b: 2, c: 3 };for (const i in obj) { console.log(obj[i]);}
Array iteration
The for...in loopshouldn't be used for Array iteration.Did you intend to use afor
loopinstead of afor-in
loop to iterate anArray
? Thefor
loop allows you to set an initializer then as well:
const arr = ["a", "b", "c"];for (let i = 2; i < arr.length; i++) { console.log(arr[i]);}// "c"