Lately I’ve been doing quite a bit of Javascript and today I’ve experienced an interesting problem. A function variable, which should be global, is logged to console. Then it is redefined as a local variable. You might assume, that the logged value would be the value of the global variable, but in such case you would be wrong, just as I was. In fact it was returning “undefined”.

Sample code:

var variable = 5;
function attempt() {
    var variable = 6;

If you want to check it yourself, here’s a JSFiddle link.

What’s happening???

This is the so called “variable hoisting” in action. If you define a variable in a function, it doesn’t matter if it’s at the top or somewhere later in the function, it will be “hoisted” to the top, but it will not be initialized. That is where “undefined” comes from.

While researching what happened I found Mozilla Developers Network, which has some great info on variable scope and hoisting.

Such behavior is unexpected to traditionally trained programmers, that’s why Douglas Crockford in his book “Javascript: The Good Parts” recommends to define all variables at the top of the function.