Table of Contents
Call Stack in JavaScript
Definition
A call stack is a system that allows an interpreter (such as the JavaScript interpreter in a web browser) to maintain track of its position in a script that calls numerous functions—what functions are presently being performed, what functions are called from inside that function, and so on.
- When a function is called by a script, the interpreter adds it to the call stack and then executes the function.
- Any functions called by that function are added to the call stack and run where their calls are reached.
- After the current function completes, the interpreter removes it from the stack and picks up where it left off in the previous code listing.
- A “stack overflow” error is generated if the stack uses up more space than it was given.
JavaScript Call Stack Example
function greeting() { // [1] Write Some code here sayHi(); // [2] Write Some code here } function sayHi() { return "Hi!"; } // call the `greeting` function greeting(); // [3] Write Some code here
JavaScript Code Explanation
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.
Note: Call stack list: - 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.
Note: Call stack list: - 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.
Note: Call stack list: - 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.
Note: Call stack list: EMPTY
Summary
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.
Understanding of JavaScript Object Functions
Web Development Framework Angular
This Post Has 2 Comments