1

enter image description here

The code:

var a=1
console.log(a)
if(true){
    a=2
    console.log(a)
    function a(){}
    console.log(a)
    a=3
    console.log(a)
}
console.log(a)  // 2   why?

Who please explain why the final result here of “a” is 2?

I have read a related question: What are the precise semantics of block-level functions in ES6? The answer is excellent. But here I still can not understand my code……

How does the function a(){} work in the block-scope when I have already declared a variable of the same name(a) in its function-scope?

Anyway, tell me why the variable a was assigned the value of 2, please.

kiranvj
  • 32,342
  • 7
  • 71
  • 76
Afei
  • 27
  • 2
  • 3
    Isn't this the same question? https://stackoverflow.com/questions/61191014/why-block-assign-value-change-global-variable – Anurag Srivastava Apr 13 '20 at 16:59
  • Don't use `function` declaration statements inside conditional code blocks. – Pointy Apr 13 '20 at 17:00
  • 3
    Very odd to have two almost identical questions about some fairly obscure semantics asked within an hour of each other as the first question by two new accounts. – Quentin Apr 13 '20 at 17:00
  • Alright...it is just a coincidence. Thank you all. ╮(‵▽′)╭ – Afei Apr 13 '20 at 17:13
  • This is really weird, if not even a bug. I would have expected the result to always be `1` - and at least in strict mode, it is. Sloppy mode works differently apparently. – Bergi Apr 13 '20 at 17:25

0 Answers0