Reputation: 3029
I wanted to learn more about when to use function expressions vs function declaration in JavaScript and stumbled across this article which has the following code snippet:
function foo(){
function bar() {
return 3;
}
return bar();
function bar() {
return 8;
}
}
alert(foo());
To my surprise, and because of hoisting, this evaluates to 8
. When a declaration gets hoisted, does it get moved all the way to the top of the function (it would be hoisted before the first bar() that returns 3) or, would it be hoisted after all other function declarations (it would be hoisted after the first bar() that returns 3)?
Upvotes: 0
Views: 81
Reputation: 81
The javascript compiler hoist the first bar function, then when it comes to second function it overrides the first bar function. That's why we are getting the output as 8
Upvotes: 2
Reputation: 96964
Hoisting occurs during the compile phase, and so the order of declarations in a given scope is preserved during hoisting. Imagine the interpreter reading the code in two passes, and in the first it only cares about what is declared in a given scope, and then a later pass actually evaluates.
This is why your example returns 8
; if the second declaration of bar
was above the first, then the call to bar()
would return 3
.
See also: MDN documentation on hoisting.
Upvotes: 1