I was browsing around the internet and came upon this JavaScript function
function foo(){
function bar() {
return 3;
}
return bar();
function bar() {
return 8;
}
}
console.log(foo());
=>8
It's really confusing why this function is returning 8 when it is called. I would assume that this code would run down the contents of the function and stop at return bar();
and return 3. What am I missing here?
This is a result of variable hoisting. function
definitions go before anything else. It really looks like this
function foo(){
var bar;
bar = function() {
return 3;
}
bar = function() {
return 8;
}
return bar();
}
"Because variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top." var MDN
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.