Search code examples
javascriptscopeconstantsecmascript-6hoisting

const variable not hoisted for immediately invoked function


I was playing around new ECMASCRIPT-6 const key word. I did not understand one particular behaviour of the keyword.

Lets say I have two functions

First case

(function(){
  console.log(_t); 
  const _t=10;
})();

and Second case

function t(){
  console.log(_y); 
  const _y=11;
}
t();

For the first case the output is (didn't understand why)

ReferenceError: can't access lexical declaration `_t' before initialization

For the second case the output is (fine)

undefined

The second case output is as expected but I'm not getting any idea why the first case result throws error. It can be inferred from the error that the variable is not hoisted. But why? I found here that const uses block scope. Has it anything to do with this scoping?

I'm using Firefox Developer Version console to run tests.


Solution

  • This is Firefox related issue as mentioned in here

    Firefox-specific notes

    The const declaration has been implemented in Firefox long before const appeared in the ECMAScript 6 specification. For const ES6 compliance see bug 950547 and bug 611388.

    Starting with Gecko 36 (Firefox 36 / Thunderbird 36 / SeaMonkey 2.33):

    {const a=1};a now throws a ReferenceError and does not return 1 anymore due to block-scoping. const a; now throws a SyntaxError ("missing = in const declaration"): An initializer is required. const a = 1; a = 2; now also throws a SyntaxError ("invalid assignment to const a").

    Also I found something here as well

    I think Firefox engine is very strict on const hoisting.

    I think this makes sense.