Repository navigation
Read 10: The Call Stack and Debugging
Ahmad Sawalqeh edited this page Nov 23, 2019
·
1 revision
A call stack is a mechanism for an interpreter:
- When a script calls a function, the interpreter adds it to the call stack and then starts carrying out the function.
- Any functions that are called by that function are added to the call stack further up, and run where their calls are reached.
- 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.
- If the stack takes up more space than it had assigned to it, it results in a "stack overflow" error.
function firstFunction(){ console.log("Hello from firstFunction");}
function secondFunction(){ firstFunction(); console.log("The end from secondFunction");}
secondFunction();
- When
secondFunction()gets executed, an empty stack frame is created. It is the main (anonymous) entry point of the program. -
secondFunction()then callsfirstFunction()which is pushed into the stack. -
firstFunction()returns and prints “Hello from firstFunction” to the console. -
firstFunction()is pop off the stack. - The execution order then move to
secondFunction(). -
secondFunction()returns and print “The end from secondFunction” to the console. -
secondFunction()is pop off the stack, clearing the memory.
The key takeaways from the call stack are:
- It is single-threaded. Meaning it can only do one thing at a time.
- Code execution is synchronous.
- A function invocation creates a stack frame that occupies a temporary memory.
- It works as a LIFO — Last In, First Out data structure.