Recently, I was experimenting with the new ECMASCRIPT-6 const keyword. There was one particular behavior of the keyword that left me confused.
Imagine we have two functions:
In the first case:
(function(){
console.log(_t);
const _t=10;
})();
and in the second case:
function t(){
console.log(_y);
const _y=11;
}
t();
Upon running the code, the output for the first case is (which puzzled me):
ReferenceError: can't access lexical declaration `_t' before initialization
While for the second case, the output turns out to be (as expected):
undefined
The result of the second case makes sense, but I couldn't figure out why the first case threw an error. The error message seems to suggest that the variable is not hoisted. But why is that? After doing some research on this resource, I learned that const
uses block scope. Could this be related to the scoping issue?
I conducted these tests on the Firefox Developer Edition console.