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

We’d love to hear your thoughts on the next set of proposals for the JavaScript language. You can find a description of the proposals here.
Please take two minutes to fill out our short survey.

Сообщение

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

Тип ошибки

Что случилось?

Попытка доступа к лексической переменной до её инициализации. Это может произойти в любом блоке, если попытаться обратиться к переменной, объявленной с помощью ключевых слов let или const до того, как им было присвоено значение.

Примеры

Неправильно

Здесь переменная "foo" заново объявляется внутри блока с помощью ключевого слова let.

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

Правильно

Чтобы изменить "foo" в теле выражения if, надо убрать ключевое слово let и таким образом избавиться от повторного объявления.

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

Смотрите также