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
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
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);