Everything is an object in javascript. Does this mean that call stack has nothing to do with the stack section of the memory and function calls are just stacked in the heap section?
1 Answer
Everything is an object in javascript
This is not true. Primitives are primitives unless you use them as objects. A number might be stored as e.g. a 32bit integer or a 64bit floating point by the JavaScript engine.
What's more important in the context of the callstack is that variables can hold values of different types, so a variable might hold different values of different size. A very naive implementation could therefore allocate pointers onto a stack and these pointers would then point to objects of different size (or primitives wrapped in some container).
Now engines are usually not naive, they can easily make assumptions that certain variables at a certain time hold certain variable types, and then they can directly allocate fixed size datastructures onto a stack.
function calls are just stacked in the heap section?
The reason why function variables are represented as a stack in memory is that a function might recursively call itself, so for one function multiple values can exist. A stack is a good choice, because the address of the variables can easily be calculated (one addition) from the stack pointer:
function fn() {
var a = 1, b = 2;
fn();
}
// how the stack of might look like (very simplified)
// v stackpointer
adress | 0 | 1 | 2 | 3 | 4 | 5
value | 1 | 2 | 1 | 2 | 1 | 2
// some pseudo Cish code
void* stackpointer = 5;
int currentB = (stackpointer)*
int currentA = (stackpointer - 1)*
However this is only that easy if the size of the variables is known. It doesn't really matter where your stack gets allocated in memory, just that all values are fixed size.
Also there is not "the stack", if you call asynchronous functions, their execution might pause, and for every paused function some form of callstack must stay in memory. So there is always a stack currently executing and eventually multiple stacks that are paused. One might say that the currently executing stack is "the stack" and that the other stacks are "in the heap", though that distinction is not very useful, especially as there might also be multiple heaps (e.g. a heap for strings, a heap for objects, ...).