Hoisting
Variable Hoisting:
- Hoisting means that when the Javascript runtime sees a 'var' keyword, it figures it out before it execute the function.
- Simplify by declaring 'var a', The var a is bound to the scope (function) before the function is executed
Example 1:
function example() {
//'a' is an undeclared variable
console.log(a); -> Crash as value is not found, walk up the scope...and cannot find it..
}
example();
Example 2:
function example() {
a = 10; -> Referred as a left hand reference, I am trying to put something in memory. It is going to walk up the scope
chain, if it hits the global scope, it will attach it to the global scope.
console.log(a); -> Right hand reference -> Will result in 10
}
example();
Example 3:
function example() {
console.log(a); -> Results in 'undefined'
var a;
}
example();
Example 4:
function example() {
console.log(a); -> Results in 'undefined'
var a = 10;
}
example();
Example 5:
Why was example 4 results in 'undefined?
var a = 10 actually means:
var a; -> Variable declaration (It will be undefined before it execute the function.
a = 10; -> Variable assignment, it gets executed in order
//So for:
function example() {
console.log(a);
var a = 10;
}
//What the compiler sees is:
function example() {
var a; -> Var a is not top
console.log(a); -> Results in 'undefined'
a = 10;
}