files/en-us/glossary/call_stack/index.md
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 {{glossary("function","functions")}} — what function is currently being run and what functions are called from within that function, etc.
function greeting() {
// [1] Some code here
sayHi();
// [2] Some code here
}
function sayHi() {
return "Hi!";
}
// Invoke the `greeting` function
greeting();
// [3] Some code here
The call stack will be empty at the very beginning, and the code above would be executed like this:
Ignore all functions, until it reaches the greeting() function invocation.
Add the greeting() function to the call stack list, and we have:
- greeting
Execute all lines of code inside the greeting() function.
Get to the sayHi() function invocation.
Add the sayHi() function to the call stack list, like:
- sayHi
- greeting
Execute all lines of code inside the sayHi() function, until reaches its end.
Return execution to the line that invoked sayHi() and continue executing the rest of the greeting() function.
Delete the sayHi() function from our call stack list. Now the call stack looks like:
- greeting
When everything inside the greeting() function has been executed, return to its invoking line to continue executing the rest of the JS code.
Delete the greeting() function from the call stack list. Once again, the call stack become empty.
In summary, then, we start with an empty Call Stack. Whenever we invoke a function, it is automatically added to the Call Stack. Once the function has executed all of its code, it is automatically removed from the Call Stack. Ultimately, the Stack is empty again.