The Call Stack defined on MDN

A call stack is a mechanism for an interpreter (like the JavaScript interpreter in a web browser) to keep track of its place in a script that calls multiple functions — what function is currently being run and what functions are called from within that function, etc.

  1. When a script calls a function, the interpreter adds it to the call stack and then starts carrying out the function.
  2. Any functions that are called by that function are added to the call stack further up, and run where their calls are reached.
  3. When the current function is finished, the interpreter takes it off the stack and resumes execution where it left off in the last code listing.
  4. If the stack takes up more space than it had assigned to it, it results in a “stack overflow” error.

Example

function greeting() { // [1] Some code here sayHi(); // [2] Some code here } function sayHi() { return “Hi!”; }

// Invoke the greeting function greeting();

// [3] Some code here

explanation

  1. When the greeting() function is invocated. It is added to the call stack list.
  2. The code inside the greeting() function is executed.
  3. The sayHi() function is invocated.
  4. The sayHi() function is added to the call stack list.
  5. The code inside the sayHi() function is executed.
  6. The sayHi() and continue executing the rest of the greeting() function.
  7. The sayHi() function is deleted from our call stack list
  8. When everything inside the greeting() function has been executed, return to its invoking line to continue executing the rest of the JS code.
  9. The greeting() function is deleted from the call stack list.
  10. The call stack list is now empty.

Understanding the JavaScript Call Stack

Essentially, a call stack is a data structure that uses the Last In, First Out (LIFO) principle to temporarily store and manage function invocation (call).

JavaScript error messages

What causes a stack overflow?

A stack overflow occurs when there is a recursive function (a function that calls itself) without an exit point. The browser (hosting environment) has a maximum stack call that it can accomodate before throwing a stack error. Hwer’s aan example of a stack overflow.

This code will run until the browser gives an error:

function callMyself(){ callMyself(); } callMyself();

stack-overflow

References

  1. https://developer.mozilla.org/en-US/docs/Glossary/Call_stack
  2. https://www.freecodecamp.org/news/understanding-the-javascript-call-stack-861e41ae61d4/
  3. https://www.freecodecamp.org/news/understanding-the-javascript-call-stack-861e41ae61d4/