1
var a; 

if (true) {
 a = {a: 2};
 function a() {}
 a.ot = '9'; 
 a = {a: 4};
 console.log('1', a);
}

console.log('2', a);

which output is

1 {a: 4}
2 {a: 2, ot: "9"}

can anyone tell me why? thanks so much

Thum Choon Tat
  • 3,084
  • 1
  • 22
  • 24
yudongqiu
  • 11
  • 1
  • compile? anway, what output were you expecting? – Jaromanda X Dec 06 '19 at 03:50
  • 2
    Does this answer your question? [What are the precise semantics of block-level functions in ES6?](https://stackoverflow.com/questions/31419897/what-are-the-precise-semantics-of-block-level-functions-in-es6) – ASDFGerte Dec 06 '19 at 03:57
  • 1
    long story short: this is one of the 634534 black magic pitfalls, that happen, when you don't "use strict"; – ASDFGerte Dec 06 '19 at 04:03

1 Answers1

1

As @ASDFGerte points out, this answer explains the answer but let me just do some bridge work from your example to the example given in the answer.

First of all, lets remove the if (true): it is only relevant that there is a block. Second, let us replace {a: ...} with plain strings. The line a.ot = '9' is also irrelevant so let us remove that. So now we are down to the following:

var a; 

{
 a = 'before func declaration';
 function a() {} 
 a = 'after func declaration';
 console.log('Inside block:', a);
}

console.log('Outside block:', a);

The output is as follows:

Inside block: after func declaration
Outside block: before func declaration

At this point it should be clearer as to how the example code from this answer applies. In essence, it is as if the code were written as follows:

var a;

{
 let b = function a() {}
 a = 'before func declaration';
 b;
 b = 'after func declaration';
 console.log('Inside block:', b);
}

console.log('Outside block:', a);
Kent Shikama
  • 3,910
  • 3
  • 22
  • 55