Skip to content

Instantly share code, notes, and snippets.

@sotayamashita
Last active May 22, 2018 01:29
Show Gist options
  • Save sotayamashita/5b18c24ba430921a898e8d8dfb31f535 to your computer and use it in GitHub Desktop.
Save sotayamashita/5b18c24ba430921a898e8d8dfb31f535 to your computer and use it in GitHub Desktop.

Question

function func() {                
  if (true) {                    
    var message1 = "hello world" 
    let message2 = "good night"  
  }                              
  console.info(message1)         
  console.info(message2)         
}

func()

Commentary

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

Life cycle

  1. Scope of a var is entered. Space is created for it. message1 is initialized by setting it to undefined.
  2. Scope of a let is entered. Space is created for it. message2 is not initialized yet. It means unuinitialized.
  3. The message1 is set to the value specified by the initializer(hello world).
  4. The message2 is set to the value specified by the initializer.(good night)
  5. Scope of a let is exited.
  6. message1 should return hello world
  7. message2 should return good night because it is uninitialized.

Issue

He/She has tried to test the code but he/she cannot get the result. see https://twitter.com/kuwahara_jsri/status/998532931680260096

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment