Last Updated: December 26, 2018
·
1.37K
· alexanderbrevig

JavaScript variable hoisting

In JS, variables are hoisted (declared) to the top of the scope.
This means that the following function:

function fn() {
    alert("Hello " + world);
    var world = "world";
}

Will actually be evaluated as:

function fn() {
    var world;
    alert("Hello " + world);
    world = "world";
}

That's why JS will not bother you about uninitialized variables, and that's why I think it's best practice to declare your variables where they will be eventually - at the top of the scope. This way you can spot problems yourself.

You could also use this: http://www.jslint.com/lint.html

The above example will alert 'Hello undefined'.