Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 558
Azeez Avatar asked Dec 11 '15 10:12

Azeez


People also ask

Why is let and const not hoisted?

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.

Can you access variable declared with var before it is declared?

Yes, you can use a JavaScript variable before it is declared, with a technique called hoisting.

When a let variable is referred before it is created it will give which error?

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.

Can't access before initialization react?

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.


2 Answers

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).

like image 44
Matthisk Avatar answered Oct 26 '22 23:10

Matthisk


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.

like image 89
Bergi Avatar answered Oct 27 '22 00:10

Bergi