Search code examples
javascriptfrontendreferenceerrorhoisting

Why does it throws reference error for b?


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 ?


Solution

  • 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