2

console.log(window.b,b) //undefined undefined
if(true){
    console.log(b) //ƒ b(){} does it get hoisted?
    b = 4
    function b(){}
    b = 3
    console.log(b) //3  Why is this variable 3
}
console.log(window.b,b) //4 4   Why is this variable 4

If the code removes this line

function b(){}

The browser will report an error VM114:1 Uncaught ReferenceError: b is not defined at line 1 console.log(window.b,b)

Can someone tell me why it works like this??

if function b gets hoisted, does it equals to

console.log(window.b,b) //undefined undefined why it doesn't cause an ReferenceError b is not defined
if(true){
    function b(){}
    b = 4
    b = 3
    console.log(b) // 3
}
console.log(window.b,b)  // ƒ b(){} ƒ b(){}

I am not a native English speaker,hope you can understand.

lei lee
  • 21
  • 5
  • 4
    Does this answer your question? [Javascript function scoping and hoisting](https://stackoverflow.com/questions/7506844/javascript-function-scoping-and-hoisting) – Darth Aug 14 '20 at 13:59
  • Check this out. https://www.w3schools.com/js/js_hoisting.asp – ismetguzelgun Aug 14 '20 at 14:13
  • I was mistaken, hoisting works in both local/global (or script) scope – Zorgatone Aug 14 '20 at 16:10
  • Hoisted should become: var b; b=4; b=function(){}; b=3; – Zorgatone Aug 14 '20 at 16:11
  • 1
    Function declarations inside `if` blocks have always been kinda wonky. [Strict mode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode) disallows this for that reason; which I recommend you always use. – TiiJ7 Aug 14 '20 at 16:12
  • Also can you add information about the browser error when you remove the b function line? Can you tell us if you’re in strict mode or not? – Zorgatone Aug 14 '20 at 16:13
  • @Zorgatone I updated my question. and I am not in strict mode, if I use the strict mode, two example throw the same `ReferenceError` at line 1. – lei lee Aug 14 '20 at 16:23
  • @TiiJ7 ok,I just want to figure out how to explain the wonky performance,is it a Bug of JavaScript? – lei lee Aug 14 '20 at 16:27

1 Answers1

2

Because your function b gets hoisted. AS soon its reaches b = 4 a value is assigned to it.

bill.gates
  • 14,145
  • 3
  • 19
  • 47