2

In the following JavaScript code saySomething() writes "Hello there!" but not "Hello you!". Does this indicate that hoisting only applies to the first var within a scope?

var whatToSay = 'Hello World!';

function saySomething() {
  if (!whatToSay) {
    var whatToSay = 'Hello there!';
  }  
  document.write(whatToSay);
  var whatToSay = 'Hello you!';
}

saySomething();

Here is a link to the JS Bin http://jsbin.com/fiyimefeso/1/edit?js,output

  • This will probably help you understand: http://stackoverflow.com/questions/7506844/javascript-function-scoping-and-hoisting – Norman Breau Jun 26 '15 at 18:25
  • @NormanBreau thank you but the link doesn't help me know why `var whatToSay = 'Hello there!'` takes precedence over `var whatToSay = 'Hello you!'`. – whatwasthat Jun 26 '15 at 18:34
  • 1
    Hoisting only creates a variable, it doesn't do assignments. – Norman Breau Jun 26 '15 at 18:37
  • JavaScript only hoists declarations, not initializations. – dansasu11 Jun 26 '15 at 18:37
  • It doesn't "take precedence" but just happens that the variable value before the **write** is "Hello there". As dansasu said, its value is unrelated to the declaration. It doesn't magically grabs the last assignment and use it for the whole function but rather merely "Hello there" is the last held value before usage – JSelser Jun 26 '15 at 18:42

1 Answers1

2

Nope. Hoisting means that var declarations happens before code execution. Var assignments happens during code execution. When hoisted, all variables has undefined values.

Proof here: http://jsbin.com/xezamexama/edit?js,output

Add type checking to comparison and it will print undefined and not "Hello you!" as you expected.

  • thank you, I hadn't considered assignment of separate of the hoisting process. Your answer explains what is happening well. – whatwasthat Jun 26 '15 at 18:42