Search code examples
javascriptlexical-scope

why the value of variable doesn't show as expected?


there is a high vote answer of lexical scope in StackOverflow(or some other q&a website, I'm not sure) describing as

function a() {

    var x
    x = 3
    function b() {
        x = 4
    }
    function c(){
        var x
        b()
    }

    c()
    print(x)
}

the answer in general is like

if(final output is 4):
    it is lexical scope
elif(final output is 3):
    it's dynamic scope

I make a conclusion:

  1. so lexical scope has nothing to do with where to invoke the function, but where to define the function.

    if lexical scope relates to where to invoke the function: b() is invoked in c(), final output should be 3

  2. normal variable all follows lexical scope rule


following is my code

let a = "before f()"

function f(){
    console.log(a) 
}

f() -->output: before f()

a = "before b() after f()"

f() -->output: before b() after f()

My Question: why invoking f() the second time it's before b() after f(), not before f()?

this is the process I think

invoking f() the second time
go to function definition and try to find value of a
go to lexical scope where it's out and up to function definition 
find a = "before f()"

Solution

  • Scope determines which variable is used and depends on where the function is declared.

    The value that is used will be the value of that variable at the time you read from it (which will be when the function is called).