Initialization order
- Initialization
- Function Declaration on first step
- var (adds to window global object: var a -> window.a) on second step
- Assignment
!NB: Further comments in block of codes are states of initialization
Example 1
(function() {
// window: {a: undefined, fo: undefined}
var a = 5;
// window: {a: 5, fo: undefined}
var fo = function f() {
// window: {a: undefined}
console.log(a);
var a = 1;
}
fo();
})();
Example 2
(function() {
// window: {a: undefined, fo: undefined}
var a = 5;
// window: {a: 5, fo: undefined}
var fo = function f() {
// window: {a: 5} // 'a' has alredy exists
console.log(a);
a = 1;
}
fo();
})();
Example 3
(function() {
// window: {a: undefined, fo: undefined}
var a = 5;
// window: {a: 5, fo: undefined}
var fo = function f() {
// window: {a: undefined, b: undefined, f2: function, e: error}
console.log('a ' + a);
console.log('b ' + b);
console.log('e ' + e);
var a = 1;
var b = 2;
e = 0;
function f2() {
console.log('f2 ' + f2);
}
f2();
};
fo();
})();