I came across the following article about variable hoisting in javascript. The article sums up the following three points.
1. All declarations, both functions and variables, are hoisted to the top of the containing scope, before any part of your code is executed.
2. Functions are hoisted first, and then variables.
3. Function declarations have priority over variable declarations, but not over variable assignments.
var showState = function() {
console.log("Idle");
};
function showState() {
console.log("Ready");
}
showState();
I understood that the code is interpreted by the javascript engine as
function showState() { // moved to the top (function declaration)
console.log("Ready");
}
var showState; // moved to the top (variable declaration)
showState = function() { // left in place (variable assignment)
console.log("Idle");
};
showState();
But, I couldn't get the meaning of the third point in the summary. Can anyone care to explain the third point? What is the meaning of the third point?
According to the explanation of the third point, the following snippet should return 8, function bar(). But it says undefined, function bar().
console.log(foo);
console.log(bar);
var foo = 8;
function bar() {
console.log("bar");
}
var foowould be hoisted BEFORE yourfunction bar()gets hoisted. so in reality your interpreted code would bevar foo; function bar()if you didn't have assignment statement, it would have beenfunction bar(); var foofoo = 8;the variable assignment andvar foo;the variable declaration part?undefinedoutside. :) I sincerely believe this is the reason behind why functions take priority over uninitialized variables.