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?
let and const hoisting An exception will be thrown if a variable declared with let or const is read before it is initialized. Note that it is the order in which code is executed that matters, not the order in which it is written in the source file.
Yes, you can use a JavaScript variable before it is declared, with a technique called hoisting.
Variables declared with let will throw a reference error when you access them before the initialisation, when their declaration statement is evaluated: let bar; // = undefined; if (bar) {} // this is fine console.
The "Cannot access before initialization" error occurs when a variable declared using let or const is accessed before it was initialized in the scope. To solve the error, make sure to initialize the variable before accessing it.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With