1

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.

enter image description here

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 scope Block(foo) is necessary.
    • Variable B is declared in function foo, so scope Closure(foo) is necessary.
    • Global Scope is necessary.

enter image description here

Is there some optimizing logic to make scope chain? I cannot found references for this phenomenon.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.