I have a question about mechanism of making scope chain in JavaScript. In the Chrome browser, the results of scope chain is different according to refer variables or not.
Let me show you an example.
EXAMPLE 1. CODE AND RESULT
var A = 'Hello'
function foo() {
var B = 'World'
function bar() {
var A = 'Junhyunny'
if (A) {
const C = 'JavaScript'
if (B) {
const D = 'Post'
function baz() {
console.log(A)
console.log(B)
console.log(C)
console.log(D)
console.dir(baz)
}
}
}
baz()
}
bar()
}
foo()
- There are five scopes in
[[Scope]]
, I expected.
EXAMPLE 2. CODE AND RESULT
var A = 'Hello'
function foo() {
var B = 'World'
function bar() {
var A = 'Junhyunny'
if (A) {
const C = 'JavaScript'
if (B) {
const D = 'Post'
function baz() {
// console.log(A)
// console.log(B)
// console.log(C)
// console.log(D)
console.dir(baz)
}
}
}
baz()
}
bar()
}
foo()
- There are only 3 scopes in
[[Scope]]
. - I guess the reasons for this result.
- Declaration for function
baz
is effected by variable B, so scopeBlock(foo)
is necessary. - Variable B is declared in function
foo
, so scopeClosure(foo)
is necessary. - Global Scope is necessary.
- Declaration for function
Is there some optimizing logic to make scope chain? I cannot found references for this phenomenon.