-3

Can someone explain below code:

What will be the value of myVar inside function b?

function a() {
        function b() {
            console.log("b", myVar); 
        }
        b();
    let myVar;    
    console.log("a", myVar);  //Look for a execution context
}
a();
Dolly
  • 2,213
  • 16
  • 38
  • It never gets initialized - it never gets a value, and is accessed before initialization, so it throws. – CertainPerformance Mar 11 '19 at 08:26
  • `let` is different to `var` - see the [temporal dead zone](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#Temporal_dead_zone) - which is not a Stephen King short story – Jaromanda X Mar 11 '19 at 08:31
  • @CertainPerformance, Isn't the myVar should be hoisted to the top inside function "a" and as b function is sitting lexically inside "a" function it should look to its upper scope(i.e parent "a") – Dolly Mar 11 '19 at 08:36

2 Answers2

0

let variables are not initialized until their definition is evaluated. Accessing the variable before the initialization results in a ReferenceError

Himanshu Pandey
  • 688
  • 2
  • 8
  • 15
  • Isn't the myVar should be hoisted to the top inside function "a" and as "b" is sitting lexically inside "a" function it should look to its upper scope(i.e parent "a") – Dolly Mar 11 '19 at 08:38
  • no, myVar are hoisted but period between entering scope and being declared where they cannot be accessed. This period is the temporal dead zone (TDZ). https://stackoverflow.com/questions/33198849/what-is-the-temporal-dead-zone – Himanshu Pandey Mar 11 '19 at 08:42
0

Declare myVar to var instead fo let. it will give you undefined. So it is a simple concept of Keyword let not concept of Hoisting inside a function. Run only the below code. you will get the same error.

console.log(number); //Reference error
let number= 1;
VB MAVANI
  • 59
  • 1
  • 2