5

var a;
console.log('1 a: ' + a);
if (true) {
    a = 1;
    function a() { };
    a = 5;
    console.log('2 a: ' + a);
}
console.log('3 a: ' + a);

The output is:

1 a: undefined
2 a: 5
3 a: 1

I can't understand the last output "3 a: 1". Why not "3 a: 5" ?

MurphyChen
  • 57
  • 4
  • 3
    Function declarations within blocks are really weird. Just like with `with`, best way to deal with it is to just never use them. – CertainPerformance Oct 29 '21 at 03:00
  • 1
    You both have local and global a variables.`a = 1` is changing the global `a`, then you declare a function a and change the value, but this local function is declared inside the if scope, so changing it to 5 does not change the global `a` with 1. – Leo Oct 29 '21 at 03:00
  • @CertainPerformance No, they're perfectly fine. The advice is not to use them in sloppy mode! – Bergi Oct 29 '21 at 15:47

0 Answers0