In this article I will give a quick overview of JavaScript hoisting and explain why sometimes your variables are not doing what you expect them to.
In the following example we have a very simple variable declaration and function:
var msg = "hello world" function sayHi(){ alert(msg) } sayHi()
If you run this through firebug you get the expected message in the browser
However if you change the code slightly you do not get the initially expected response. When you run the following code you get ‘undefined’ as the answer when you would possibly expect to see “hello world”
var msg = "hello world" function sayHi(){ alert(msg) var msg = "hello galaxy" //<--- new line of code } sayHi()
This is due to what is called “JavaScript hoisting” and there is an excellent article on it here - http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html. What is basically happening is that although you did not write it, the function level scoping of var msg = “hello galaxy” is declaring the variable msg at the top of the function before anything else executes.
So what you are really doing is this:
var msg = "hello world" function sayHi(){ var msg alert(msg) msg = "hello galaxy" } sayHi()
I recommend you read the article I mentioned and understand how JavaScript scoping differs from other programming languages.
