Javascript Call stack
This article is about the JavaScript call stack. Call stack works only if we use a function.
What is call stack?
The stack is a part of the memory used to keep track of function calls. Incall stack the default function is “anonymous”.
When we call a function, that funciton is going to be pushed on top of the stack & local variables of that funciton are created in the local scope
When a control exits a function it is going to be popped out of the stack & the created local variables of that function are deleted from the local scope.
We know that local variables are created as soon as the control enters the function body. And the global variables will be available throughout script execution. Check this linkLocal vs Global Scope of Variables in JavaScript, if you don’t know the difference between local and global variables
How works call stack in the function
function h(){
document.write("h function","<br/>"); }
function g(){
document.write("g function", "<br/>"); }
function f(){
document.write("f function", "<br/>"); }
// calling function
f();
g();
h();
/*
Output:
f function
g function
h function
*/
In the above code ,we have three javascript function called h(), g() and f(). We have created h, g, and f in order, But we have the function run in f, g, and h order Because that’s what we called the function. So we can create the function however we want but we have to do it correctly while calling the function.
Steps:
- Before calling a function on the call stack, the default function “anonymous” is inserted into the stack first.
- Then, in the above code, we called the f() function first so the f() function is inserted and after the f() function completes it will remove from the stack.
- Then we called the g() function second so the g() function is inserted and after the g() function completes it will remove from the stack.
- Then we called the h() function third so the h() function is inserted and after the h() function completes it will remove from the stack.
- Finally, after all the functions are finished, the “anonymous” default function will be removed.