2
votes
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
3
Why would that throw error when you've defined it tmp = 'abc'; - Tushar
Your original usage of tmp = 'abc' is implicitly declaring a var. - James Collier
Please show us your babel settings. This definitely should throw an error, albeit it might not if you are transpiling in loose mode. - Bergi
May be the problem is babel ? i run this code in chrome,it works - Runjuu
@Bergi here is my .babelrc file content { "presets":[ "babel-preset-es2015" ], "plugins": [ "babel-plugin-transform-es2015-destructuring", "babel-plugin-transform-es2015-modules-commonjs" ] } - Runjuu

3 Answers

2
votes

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

  • node.js already implemented let - but it works correctly only in strict mode. You should use it.
  • babel does not appear to transpile the TDZ by default, as it is quite complicated and leads to lengthy code. You can however enable it with the es6.blockScopingTDZ/es6.spec.blockScoping option (but I'm not sure whether this worked in Babel 5 only and what happened in Babel 6 to them).
0
votes

Statement

tmp = 'abc';

is not elegant but still OK in normal mode (except let keyword which is not allowed outside strict mode). It will simply create global variable. However, the code is not correct and will throw an error only when you executed this code in "strict mode". In this mode you have to declare all variables with one of this keywords:

  • var
  • let
  • const

'use strict'
if(true) {
  tmp = 'abc';
  console.log(tmp);//which should throw referenceError and now it does
                  
  let tmp;
  console.log(tmp);

  tmp = 123;
  console.log(tmp);
}
-2
votes

No, it shouldn't throw a reference error.

The variable is implicitly declared (in the global scope) when you assign to it.

Then, later, you declare a new variable with the same name but a tighter scope. The new variable is not hoisted because it is declared using let.

I can't give a more precise answer, because you did not explain why you think you should get a reference error.