0

When i am using var keyword to declare a variable then JS engine is assign default value to "message" at creation stage

console.log(message); //undefined       
var message = "My message";

but with let keyword

console.log(message); //message is not defined       
let message = "My message";

why this unexpected result or it is something changed in ES6?

Jeroen Heier
  • 3,520
  • 15
  • 31
  • 32
Aman Rai
  • 11
  • 1
  • Related to hoisting, see https://www.vojtechruzicka.com/javascript-hoisting-var-let-const-variables/ – xwlee Jan 25 '19 at 05:53
  • 1
    Nothing is _changed_ in ES6; `let` was introduced in ES6. – Sнаđошƒаӽ Jan 25 '19 at 05:55
  • Because 'var' is a function scoped where as 'let' is block scoped. So you can access 'var variable' within the function that is why it is giving output as undefined. And 'let variable' scope will start after you define it. – Urja Ramanandi Jan 25 '19 at 05:57

1 Answers1

3

This is because of the creation of Temporal dead zone with let

let bindings are created at the top of the (block) scope containing the declaration, commonly referred to as "hoisting". 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.

Mamun
  • 66,969
  • 9
  • 47
  • 59