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

Message

ReferenceError: assignment to undeclared variable "x" (Firefox)

Error type

ReferenceError

What went wrong?

A lexical variable was accessed before it was initialized. This happens within any block statements, when a let or const is accessed before it's initialization.

Examples

Invalid cases

In this case, the variable "foo" is redeclared in the block so isn't initialized.

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

Valid cases

To make "foo" change inside the if statement you can't redeclare inside the new block statement.

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

See also

Document Tags and Contributors

Tags: 
 Contributors to this page: johnjago, jonathanKingston
 Last updated by: johnjago,