Interview JS Part 1 - Call Stack (Inspired by Colt Steele)

Interview JS Part 1 - Call Stack (Inspired by Colt Steele)

Why should we care?

  • It's fundamental to how JS works

  • It's helpful for debugging, almost all browsers come with debugging tools which help us see what all is happening at any time with the call stack.

What is a Call Stack?

We can consider it as a to-do list. A to-do list of function invocations. A function may have cascading function calls taking place. But mainly JavaScript is a single-threaded language, we will ignore the thread pooling effect taking place so JS can do a single task in a single unit of time.

So it has to keep track of the history of what all executions are to be made and what all things will be returned. Mainly which functions are invoked and which are waiting to get invoked.

To-Do List

Last In, First Out

/*Call Stack*/
/*
--------------
| something  |
--------------
|   multiply |
--------------
|     main   |
--------------
*/
function main() {
     multiply()
}

function multiply() {
      something()
}

function something() {
      console.log("Hello")
}

main()
  • Whenever you invoke a function, the details of the invocation are saved to the top of the stack( pushed to the top )

  • Whenever a function returns, the information about the invocation is taken off the top of the stack (popped off the top)

Stack Frame Contents

  • The function that was invoked
  • The parameters that were passed to the function
  • Current line number

If one function calls another and that function calls the same function they will get into the error of Maximum Stack Size exceeded. You can see this in debugger tools of any browser.