JS Hoisting

In JavaScript, a variable can be declared after it has been used.
In other words; a variable can be used before it has been declared.
Basically how javascript engine works

1
2
3
4
5
var myvar = 'my value';
(function(){
alert(myvar); // undefine
var myvar = 'local value';
})();

The reason why myvar is undefine is because in js engine variable is first declared.
(variable declaration is hoisted to top)

The following code is how to the engine interpreted:

1
2
3
4
5
6
var myvar = 'my value';
(function(){
var myvar;
alert(myvar); // undefine
var myvar = 'local value';
})();

That’s why in the book the javascript the good part, the author suggest that we always
place variable in the top of the function.

Another thing to note is function is hoisted to the top but not function expression.
For example:

1
2
3
4
5
6
(function(){
newFunction(); // will alert hello world
function newFunction(){
alert('hello world');
}
})();

1
2
3
4
5
6
(function(){
newFunction(); // will not alert hello world
var newFunction = function(){
alert('hello world');
}
})();

The second code snippet doesn’t work because function expression get hoisted to the top but not the expression.