0

I know that var gets hoisted in JS. So the below code gives me undefined:

i=100
function f(){
    console.log(i);
    var i=200;
}
f();

But I was surprised to see that the below code give me an error:

i=100
function f(){
    console.log(i);
    const i=200;
}
f();

Are const hoisted? If so, then why do I get an error?

codingsplash
  • 4,785
  • 12
  • 51
  • 90
  • 2
    In a sense, no, you can't reference a variable within its TDZ – CertainPerformance Mar 01 '19 at 05:19
  • @CertainPerformance What is TDZ? Also, I know that const is blocked scope. But why is the global variable not accessible before the const declaration? – codingsplash Mar 01 '19 at 05:20
  • 1
    In ECMAScript 6, accessing a let or const variable before its declaration (within its scope) causes a ReferenceError. The time span when that happens, between the creation of a variable’s binding and its declaration, is called the temporal dead zone. – Fullstack Guy Mar 01 '19 at 05:27
  • 1
    @codingsplash because it would not be "before the const" it would be "inside the function" and the function body consists only of a single *block*; before or after the const doesn't matter at this point, it's one block. So you can not have two declarations for the same variable in the same scope, and the innermost wins, the `const`; but now you're trying to access a block scoped variable before it's definition. – Thomas Mar 01 '19 at 05:56

0 Answers0