function func() {
if (true) {
var message1 = "hello world"
let message2 = "good night"
}
console.info(message1)
console.info(message2)
}
func()
function func() { // (1)
if (true) { // (2)
var message1 = "hello world" // (3)
let message2 = "good night" // (4)
} // (5)
console.info(message1) // (6)
console.info(message2) // (7)
}
< undefined
func()
< hello world
< Uncaught ReferenceError: message2 is not defined
- Scope of a
var
is entered. Space is created for it.message1
is initialized by setting it toundefined
. - Scope of a
let
is entered. Space is created for it.message2
is not initialized yet. It means unuinitialized. - The
message1
is set to the value specified by the initializer(hello world
). - The
message2
is set to the value specified by the initializer.(good night
) - Scope of a
let
is exited. message1
should returnhello world
message2
should returngood night
because it is uninitialized.
He/She has tried to test the code but he/she cannot get the result. see https://twitter.com/kuwahara_jsri/status/998532931680260096