0

I just don't understand the reason behind hoisting.

var a = 10;

function test() {
    alert(a);
    var a = 20;
}

I am getting undefined as the value of a due to JavaScript hoisting. Any specific reason behind putting all the declaration at the top.

Jonathan
  • 8,771
  • 4
  • 41
  • 78
Pavan Tiwari
  • 3,077
  • 3
  • 31
  • 71
  • Any specific reason why you want to use two different vars with the same name in one scope? – Jonathan Jan 30 '16 at 11:01
  • the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting) would explain it for you. Not sure if it's sufficient enough. – KarelG Jan 30 '16 at 11:02
  • 1
    It doesn't matter. Just declare your variables first, then move on with your life. There are much better things to worry about. Anyway, there are dozens of answers on SO on this topic, please search for them. –  Jan 30 '16 at 11:07
  • var a = 10; is private variable outside of test function and after calling test function, in statement alert(a), a is undefined because a is private not public/global. and again you are declaring and assigning var a which is private for test function. I think you want to access both private variable. so just make global by removing "var" from variable "a". – Drone Jan 30 '16 at 11:16
  • [Two words about "hoisting"](http://dmitrysoshnikov.com/notes/note-4-two-words-about-hoisting/) – Andreas Jan 30 '16 at 11:18

0 Answers0