javascriptecmascript-6babel-node

Why does this code not result in a ReferenceError?


if(true) {
  tmp = 'abc';
  console.log(tmp);//which should throw referenceError but not

  let tmp;
  console.log(tmp);

  tmp = 123;
  console.log(tmp);
}

This code results in

abc
undefined
123

Why does the first console.log(tmp) not throw an error?


why it should throw a referenceError

In ECMAScript 2015, let will hoist the variable to the top of the block. However, referencing the variable in the block before the variable declaration results in a ReferenceError. The variable is in a "temporal dead zone" from the start of the block until the declaration is processed.


the problem is bable settings,i think.
so,maybe it is a bug of babel? https://github.com/babel/babel.github.io/issues/826


Solution

  • You are correct, in ES6 this does throw an exception. There's two reasons why it doesn't for you: