m2l5la
Last Updated: February 25, 2016
·
1.102K
· alexanderbrevig
Feb007acc38e70d57f7b4c205f7e8b26

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'.

Say Thanks
Respond