JavaScript variable hoisting

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

js1

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()

js2
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()

js3

I recommend you read the article I mentioned and understand how JavaScript scoping differs from other programming languages.

5 thoughts on “JavaScript variable hoisting

  1. Marky, tried to put the $(‘.panelDemo’).shadow(‘raised’); in an afterpageload event wich gives me an error : Script interpreter error, line=1, col=1: [ReferenceError] ‘$’ not found
    When I put it in a button everything works.
    Guess must be a problem of load order ? How can I solve this ?

  2. Marc,

    ‘$ not found’ means jQuery is not loaded yet. In my sample database I have jQuery loaded as a theme. If you want to add it to your XPage directly try adding this to the top of the XPage source. This is not ideal for production but will get you going

    Add the following to your XPage at the bottom of the source code

    $(document).ready(function(){
    $(‘.panelDemo’).shadow(‘raised’)
    })

    hit me up on skype if you need any other help 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s