0

Recently I attended a interview for Frontend development, The interviewer came up with a problem which made me doubt my confidence on javascript. The question is

   function some() {
       console.log(a) // undefined
       console.log(b) // Reference Error: cannot access b before initialization.
       var a = 10;
       let b = 15
   }

I understood hoisting is happening here, but i am not sure why b throwed reference error. Could anyone please explain ?

  • Read docs on let. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let – epascarello Jul 28 '20 at 13:46
  • Please refer how let works https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let – Ritu Jul 28 '20 at 13:47
  • 1
    @Akshay Bande: No, hoisting occurs with let too. But it is inaccessible before initialization. Google temporal dead zone for more info. – CherryDT Jul 28 '20 at 13:49
  • Also relevant [What is the temporal dead zone?](https://stackoverflow.com/q/33198849) – VLAZ Jul 28 '20 at 13:50

1 Answers1

0

Unlike variables declared with var, which will start with the value undefined, let variables are not initialized until their definition is evaluated. Accessing the variable before the initialization results in a ReferenceError. The variable is in a "temporal dead zone" from the start of the block until the initialization is processed.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let