javascript エラー「Uncaught SyntaxError: for-in loop variable declaration may not have an initializer.」の解決方法

javascript エラー「Uncaught SyntaxError: for-in loop variable declaration may not have an initializer.」の解決方法

javascriptで、エラー「Uncaught SyntaxError: for-in loop variable declaration may not have an initializer.」が発生した場合の原因と解決方法を記述してます。厳格モード「use strict」を使用した時のみ発生します。

環境

  • OS windows11 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 108.0.5359.99

エラー内容

以下のコードで発生。

'use strict'

let obj = {a: 1, b: 2, c: 3 };

for (let i = 0 in obj) {
  console.log(obj[i]);
}

エラーメッセージ
※厳格モードの「use strict」のみ発生します。

Uncaught SyntaxError: for-in loop variable declaration may not have an initializer.

画像

firefox(バージョン107)では、以下のエラーとなります。

Uncaught SyntaxError: a lexical declaration in the head of a for-in loop can't have an initializer

画像

原因

「for in」 に初期値は必要ないため

解決方法

初期値を設定しない

'use strict'

let obj = {a: 1, b: 2, c: 3 };

for (let i in obj) {
  console.log(obj[i]);
}

実行結果