简体   繁体   中英

Why is a variable's value not updated as expected before being output?

I know I should not submit a question with this title, but I am really confused by the following code. anyone can explain why the last line print 1?

enviroment: chrome 80.0.3987.163

 console.log(foo) // undefined if (true) { foo = 1 console.log(foo) // 1 function foo() { console.log("a") } console.log(foo) // 1, function foo is hoist foo = 2 console.log(foo) // 2 } else { function foo() { console.log("b") } } console.log(foo) // 1, why?

if remove the function declaration, it's OK.

 console.log(foo) // undefined if (true) { foo = 1 console.log(foo) // 1 foo = 2 console.log(foo) // 2 } else { function foo() { console.log("b") } } console.log(foo) // 2

Well, after the function declaration inside the if block, the JS engine thinks that you're referring to the function. If you change the function name it should work properly.

console.log(foo) // undefined
if (true) {
   var foo = 1;
    console.log(foo, 'foo1') // 1
    function foo2() {
        console.log("a")
    }
    console.log(foo, 'still foo1') // 1, function foo is hoist
    foo = 2
    console.log(foo, 'foo2') // 2
} else {
    function foo() {
        console.log("b")
    }
}

console.log(foo) // 1, why?

This first foo is the global scope

after the function with the same name, it was identified as a local scope ie it become a local scope within that function but if you change the function name everything should work normal ie foo will now be of value 2

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM