1

Lets say we have a sequence of functions being executed in the global scope, like so:

function second() {}

function first() {
  second();
}

first();

When does first get added to the call stack?

Does it get added upon invocation, or does it get added after it calls second (and the execution context is now inside of second) ?

Andrew Aponte
  • 560
  • 4
  • 17
  • 3
    I would say: when it's actually called. – PM 77-1 Sep 30 '14 at 00:58
  • Put a `debugger;` statement at the top, step through the code and watch the call stack grow. –  Sep 30 '14 at 01:10
  • See this answer to an unrelated question for a long discussion of the call stack (and how closures are related): http://stackoverflow.com/questions/26061856/javascript-cant-access-private-properties/26063201#26063201 – slebetman Sep 30 '14 at 01:12

2 Answers2

3

A function is "added to the stack" when it is called. While a "call stack" implementation is not specified in ECMAScript 5th edition it does define the virtual behavior in 10.3 Execution Contexts:

When control is transferred to ECMAScript executable code, control is entering an execution context. Active execution contexts logically form a stack. The top execution context on this logical stack is the running execution context [ie. currently running function]. A new execution context is created whenever control is transferred from the executable code associated with the currently running execution context to executable code that is not associated with that execution context. The newly created execution context is pushed onto the stack and becomes the running execution context.

It is not technically the function that is part of the stack, but rather the execution context created from invoking the function.

This also agrees with more general Call Stack concept where the active/current function context is also part of the stack.

In computer science, a call stack is a stack data structure that stores information about the active subroutines [including the subroutine currently running] of a computer program .. the details are normally hidden and automatic in high-level programming languages..

Using this definition also ensures a function is never running "off the stack" - which agrees with such a concept from other languages/environments and JavaScript developer tools.

user2864740
  • 60,010
  • 15
  • 145
  • 220
1
function second() {/* 3rd code here will be executed once second is called */}

function first() {
  // 2nd code here will be executed before second(); is called
  second();
  // 4th code here will be executed after second(); is called and all its code has been executed
}

// 1st code here will be executed before anything is called
first();
// 5th code here will be executed when everything has been called.
Nathan Parker
  • 308
  • 2
  • 14