JavaScript variable hoisting
JavaScript has functional scope, this means that any variable you declare within a function will be available anywhere in that function. This might catch you off guard if you come from a block scope language like C# or Java where a variable declared within a for statement stays within that statement. JavaScript engines (V8, SpiderMonkey, Chakra...etc) accomplish this by hoisting variable declarations to the top of the function definition so the following code:
var doStuff = function() {
console.log('Hello stuff');
var A = 'Hello';
};
Will actually end up looking like:
doStuff = function() {
//only the declaration is hoisted
//the definition stays in its place.
var A;
console.log('Hello stuff');
A = 'Hello';
};
This behavior if not anticipated can be a cause of bugs and unexpected results:
//Variable hoisting playground.
(function () {
'use strict';
try {
//These two calls will log 'undefined'
//as if we had written var i,x; in the line above
console.log(i);
console.log(x);
//this will throw a reference error.
//This variable does not exist and will throw.
console.log(thisWillBreak);
} catch (ex) {
//reference error.
console.log(ex);
}
//we will create a code block and declare a variable
for (var i = 0; i <= 2; i++) {
var x = i;
};
//we can access this variable outside of the block
console.log(x);
//this will be undefined as the declaration was hoisted
//but the definition was not
console.log('a is %s', a);
var a = "a";
console.log('a is %s', a);
}());