简体   繁体   中英

ReferenceError is not throwing when accessing 'let' variable before declaration

I have tried to execute the below code in Firefox V30.0 Scratchpad:

function do_something() {
  console.log(foo); // ReferenceError
  let foo = 2;
}
do_something();

The expected behavior is that my program should throw Reference Error, because I am accessing a let variable before it's declaration. But, I am not getting the expected behavior, the program got executed and the result is as below

undefined

Can you explain me, why is it behaving so?

According to the MDN compatibility table , Firefox does support the temporal dead zone semantics only since v35.

Also you should always make sure to be using strict mode. Some ES6 features are not available in sloppy mode, due to concerns about breaking the legacy web. It should not affect this specific case though, despite Firefox' already long history of let usage.

Let variables in ES6 are hoisted to the top of the block where they are declared in. Reference of the variable before its declaration will result in a ReferenceError ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#Temporal_dead_zone_and_errors_with_let ). Thus you are correct to expect a ReferenceError to happen in this case.

The reason why the ReferenceError isn't happening in this case is because FF 30 does not support the so called "temporal dead zone". A good place to find out if browsers support specific parts of the ES6 spec is Kangax's Ecmascripts compatibility table ( https://kangax.github.io/compat-table/es6/#test-let ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM