When using JavaScript, you declare a variable using the var keyword.

var myvariable = "a value";

These variables are globally accessible unless they are defined within a function. Javascript performs an operation known as “hoisting” when it compiles which draws all the declarations to the top of the page.

Here is a piece of code:

var test = "my test";
alert(test);

When run, the above will display “my test” in an alert, as you would expect.

Consider this:

var test = "my test";
alert(test);

function testMe() {
    alert(test);
    var test = "another test";
    alert(test);
}

testMe();

The above will display “my test” and then an “undefined” error and then “another test” in an alert. This is because we have declared a function variable within the function testMe function and this overrides the global state.

If we refactor the code as so:

var test = "my test";
alert(test);

function testMe() {
    alert(test);
    test = "another test";
    alert(test);
}

testMe();

Because we have not used the var keyword, the variable exists throughout, and the alerts you get will be “my test” and then “my test” and finally, “another test”

Its very important to remember this, as when you have some large functions, you could be getting obscure results you could be looking for a long time to find the issue.

 

 

 

By admin

One thought on “Javascript Hoisting”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.