The call stack in the most basic sense is a data structure that functions on a last in first out principal to temporarily store and manage functions when they are invoked(called). Another thing to keep in mind about the call stack is, it is single threaded. Being single threaded means it only processes one command at a time. In this case if our call stack contains more than one function invocation, the last function that was invoked would resolve first. A simple example of this is:

Call Stack:

  • first function invocation
  • second function invocation
  • third function invocation

In this example the third function invocation would resolve first since it was the last function invocation to be pushed into the stack, when the third function invocation is finished resolving it is popped off the list and the next function invocation on the call stack is the second function invocation. This process continues until we pop everything off the call stack and we return to our global execution context.

*as an aside the global execution context is the environment in which our code lives. In a way this is our global scope.*

A simple example in which the call stack is utilized is when a function invokes another function. When the parent function is invoked, it is pushed into the call stack, as we are resolving the parent function we hit the child function within, the child function is pushed on to the call stack and it is now the current function being resolved, after it is done running, it is popped off the call stack and the parent function resumes after the child function was invoked.

Our code is executed in this order:

  1. Functions are defined and saved to memory.
  2. conversation function is invoked and pushed onto the call stack.

Call stack:

- conversation

3. console.log(‘Hello’) within conversation is executed.

4. body function is invoked and pushed onto the call stack.

Call Stack:

- converstation

- body

5. console.log(‘What nice weather we’re having’, ‘Yes, what a lovely day!’) within body is executed.

6. body function is resolved and popped off the call stack.

Call Stack:

- conversation

6. console.log(‘GoodBye!’) is executed.

7. conversation function is resolve and popped off the call stack.

Call Stack:

Call Stack is empty so whenever a function is invoked it will be pushed into the call stack and the process will repeat.