1

I have some trouble to understand the Javascript execution context

see below code:

<script >    

  var global_var;
  first();

  function first() {
    var first_var = 'a';
    second();
  }

  function second() {
    var second_var = 'b';

    console.log(first_var);
    console.log(second_var);
  }

  console.log('in the outer');
  //second();  

</script>

Based on my understanding, when first function call the second function, the second function is inside first function's execution context, so, the second can also access first function's properties, here is first_var

But, the actually output in function second display "first_var is not defined"

I am confused, could some one give me some explanation?

Thanks in advance.

2 Answers 2

2

Scoping is based in the lexical structure of the code, not the dynamic runtime relationship between functions (the "thread of execution"). The lexical structure is the static organization of the code; the "nesting" of function inside function.

In your case, the "second" function is declared outside of the "first" function, so the local variable in "first" is not visible to the code in "second".

If you were to move the "second" function inside "first":

function first() {
  function second() {
    var second_var = 'b';

    console.log(first_var);
    console.log(second_var);
  }
  var first_var = 'a';
  second();
}

then the variable would be visible.

Sign up to request clarification or add additional context in comments.

Comments

0

JavaScript has two scopes: global and function. (ES6 will introduce block scope with let and const, but for the sake of discussion, just assume the first two.

What this means is that variables defined in a function are only visible within that function. This has nothing to do with execution context.

So, in your example, first_var is only visible in first, second_var is only visible in second, global_var is visible globally because its not defined in a function.

Execution context comes into play with how this is defined, but that is another question and another topic entirely.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.