I'm learning call stack and I know it's in a 'first in last out' order, but why is JS code executed in a top to bottom order? Shouldn't the last item in the call stack (which is the first item to be popped out) be executed first?
I'm learning call stack and I know it's in a 'first in last out' order, but why is JS code executed in a top to bottom order? Shouldn't the last item in the call stack (which is the first item to be popped out) be executed first?
Without getting very technical, think of the following code,
function squared(value) {
return value * value;
}
function cube(value) {
return squared(value) * value;
}
cube(3);
Now, when the function cube is called, it's pretty obvious that, for the function cube to return it's computed value, it should compute the value of squared first and multiply the returned value.
This is the reason why inner functions are always executed first and then followed the outer functions because the outer functions might depend on the value returned by the inner functions.
Converting this to a stack, the call stack would look like
| |
--
cube is called, it is inserted into stack.|cube|
----
cube calls function squared, squared is inserted into the stack.|squared|
| cube |
-------
squared does not call any more function, so function squared is popped from the stack, executed and the value is returned to cube|cube| //squared()
----
cube is popped from the stack, executed and the value is returned to the invoker.| | // cube() * returned value from squared()
---
This is pretty much a very simple explanation of why a stack is used for function invocation and is pretty much used in all programming languages.