Home | << Previous | Next >>
- Automatic hoisting of variable declaration to the top of its enclosing scope.
- Variables as well as functions are hoisted.
- Anonymous functions could have issues with hoisting.
In snippet 1, the variable foo is hoisted in global scope. It can be visualized as mentioned in snippet 2
"use strict"
console.log(foo); // undefined
var foo = 1;
"use strict"
var foo;
console.log(foo);
foo = 1;
In snippet 3, the function moo is hoisted in global scope. It can be visualized as mentioned in snippet 4
"use strict"
moo(); // prints moo
function moo() {
console.log('moo');
}
"use strict"
function moo() {
console.log('moo');
}
moo();
Snippet 5 can be visualized as mentioned in snippet 6. Since we cannot invoke a function on undefined. We will get an error.
"use strict"
moo(); // error
var moo = function() {
console.log('moo');
}
"use strict"
var moo;
moo();
moo = function() {
console.log('moo');
}
moo();