0

I'm trying to understand how does execution stack work in javascript.

var x = 1;

function f1() {
  console.log(x);
}
function f2() {
  var x = 2;
  f1();
}

f2();

When we declared x as a global variable and those 2 functions, they are stored in global scope object along with 2 function closures. Once we called f2(), a new scope object of f2() created and prepended to global scope object. f1() will be called in f2() so a new scope object of f1() will be prepended to f2()'s scope object. Since f1() doesn't have 'x' and any local variables, it will lookup 'x' in f2()'s scope object and log '2' to the console.

My question is why does console output '1'?

I forget to mention that function calls will push new execution context onto execution stack and points to current scope object

Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
xxddd_69
  • 83
  • 1
  • 7
  • I forget to mention that function calls will push new execution context onto execution stack and points to current scope object – xxddd_69 Jan 24 '21 at 00:05
  • this question is just about variable scope, the f2 function have is own x variable, witch is not usable outside the f2 function – Mister Jojo Jan 24 '21 at 00:11
  • "*f1() will be called in f2() so a new scope object of f1() will be prepended to f2()'s scope object.*" - no. The call stack and the scope chain are two different things. – Bergi Jan 24 '21 at 00:49
  • Did you have a look at https://stackoverflow.com/questions/111102/how-do-javascript-closures-work? If yes, how did it not answer your question? – Bergi Jan 24 '21 at 00:51
  • Does this answer your question? [How do JavaScript closures work?](https://stackoverflow.com/questions/111102/how-do-javascript-closures-work) – Cat Jan 24 '21 at 01:03
  • [This "better programing" article](https://medium.com/better-programming/execution-context-lexical-environment-and-closures-in-javascript-b57c979341a5) will probably tell you more than you ever wanted to know about this issue. – Cat Jan 24 '21 at 01:06

1 Answers1

0

This is because f2 creates a new variable called "x" in the f2 scope, and it isn't visible anywhere else. To fix that you could just get rid of the "var " to make x = 2;.

Timothy Chen
  • 431
  • 3
  • 8
  • Redeclaration makes it function scope? but f1()'s scope object will point to f2()'s, it should be able to look the value? – xxddd_69 Jan 24 '21 at 00:17
  • Yes, according to MDN, "A function serves as a closure in JavaScript, and thus creates a scope, so that (for example) a variable defined exclusively within the function cannot be accessed from outside the function or within other functions.", from https://developer.mozilla.org/en-US/docs/Glossary/Scope, no variable in one function, can be accessed in another function, which means that the scope objects don't point somewhere else or anything like that. – Timothy Chen Jan 24 '21 at 00:24