Can someone explain to me why (1) returns 11
where (2) returns undefined
. what is the effect of function blocks/declarations to hoisting ?
// (1)
var boo = 11
console.log(boo) // 11
var boo = 10
// (2)
var boo = 11
function foo() {
console.log(boo)
var boo = 10
}
foo() // undefined
JavaScript hoisting within functions means that the declaration of variables are moved to the top of the function block. When you enter foo()
, var boo
is redeclared instantly even though you have not reached it (because the JS engine knows that this declaration exists within the function). Accordingly, the reason that it is undefined is because it has only been declared, you don't assign a value until the following line.
In reality, this is not a situation you should find yourself in if you declare variables in an appropriate scope and don't redeclare variables with the same name, but I understand your curiosity.
You can read more about this here.