2

First of all, I call func1 and so it gets on top of the global execution context. And then it calls func2. What I wanna know is, after calling func2, does func1 immediately return or get off the execution stack? Or is it like, first func2 gets on top of func1 execution context, it returns and then func1 returns and finally we're back to global execution context?

    func1();


function func1 () {

 func2();
}


function func2 () {

 const x = 2;
}
  • It works like a stack, but there's something called [tail call optimization](http://2ality.com/2015/06/tail-call-optimization.html). – PeterMader Feb 12 '18 at 16:31
  • Related [Explain the concept of a stack frame in a nutshell](https://stackoverflow.com/questions/10057443/explain-the-concept-of-a-stack-frame-in-a-nutshell) – Liam Feb 12 '18 at 16:34
  • Also be wary that once you [get async methods (and you will) your call stack gets a lot more complicated](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Liam Feb 12 '18 at 16:35
  • @peterMader this is not recursion. I think its an optimization thing, and i dont think that its really benefitial to optimize this – Jonas Wilms Feb 12 '18 at 16:38

2 Answers2

3

Function calls are implemented as a stack. When func1 is called, it immediately calls func2. When func2 returns, it returns to the scope of func1 and continue from there. Browser optimizations might realize that there are no more instructions after func2() and skip the chain back up, but that's implementation-dependent.

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
0

In your example, func1 might immediately return after having called func2() since there is no further code to run, but in general that is not the case. Consider

function func1() {
    const message = "example";
    func2();
    console.log(message);
}

then the log would still run in the execution of func1 after having popped the execution context of func2() (when returning from there).

Execution contexts are managed in a stack - the call stack - and will get pushed and popped only one at a time. When popping a stack frame, it resumes execution where it left off when the stack frame was pushed.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375