ReferenceError: can't access lexical declaration`X' before initialization

この記事はまだボランティアによって 日本語 に翻訳されていません。ぜひ MDN に参加して翻訳を手伝ってください!
この記事を English (US) で読むこともできます。

Message

ReferenceError: can't access lexical declaration `X' before initialization (Firefox)
ReferenceError: 'x' is not defined (Chrome)

Error type

ReferenceError

What went wrong?

A lexical variable was accessed before it was initialized. This happens within any block statement, when let or const declarations are accessed before they are defined.

Examples

Invalid cases

In this case, the variable "foo" is redeclared in the block statement using let.

function test() {
  let foo = 33;
  if (true) {
    let foo = (foo + 55); 
    // ReferenceError: can't access lexical 
    // declaration `foo' before initialization
  }
}
test();

Valid cases

To change "foo" inside the if statement, you need to remove the let that causes the redeclaration.

function test(){
   let foo = 33;
   if (true) {
      foo = (foo + 55);
   }
}
test();

See also

ドキュメントのタグと貢献者

 このページの貢献者: fscholz, johnjago, jonathanKingston
 最終更新者: fscholz,