I come from a C++ background, where I’m used to local variables typically being stored on the stack, while dynamically allocated objects are stored in the heap. I’m trying to understand if JavaScript handles stack and heap memory similarly.
In JavaScript, I wrote the following code:
function createTestObject() {
const test = {};
test.x = 4;
test.y = 5;
test.z = 6;
}
createTestObject();
C++ code :
class temp{
public:
int x;
int y;
int z;
};
int main (){
temp*test=new temp(); // test is stored in stack
return 0;
}
In C++, always test
( a pointer to an object ) to be stored on the stack, with the actual object data residing in the heap . ( like in this link ) that means the function scope can not see what in the heap ( the function scope can access the heap only through a pointer and that pointer in the stack ( the function scope can only see what in the stack ) )
But, from the comments of this answer
in JavaScript ( V8 ) , in some cases the test
reference itself can sometimes be placed in the heap.
my question : in those cases in JavaScript ( V8 ) how can the function scope see what in the heap ( because the test
reference itself in those cases is placed in the heap ) ?
Does that mean in some cases in JavaScript ( V8 ) the heap and the stack can be the same thing so the function scope can access the heap (which is also the stack in those cases ) ?
In C++, always
test
( a pointer to an object ) to be stored on the stack
Usually, but not always. For example, when compiling your snippet with optimizations, the allocation is optimized out and test
isn't stored at all. With a slight tweak to the snippet, it might be kept in a register rather than on the stack. Lambda functions that capture local variables but survive the lifetime of the function that created them also need to store the captured references off-stack (although in that case you could argue that conceptually that's a copy of the local variable on the stack, rather than the variable itself).
in JavaScript ( V8 ) how can the function scope see what in the heap
Somewhere in the function's stack frame there's a pointer to a heap-allocated data structure that holds the values of heap-allocated local variables.
Does that mean in some cases in JavaScript ( V8 ) the heap and the stack can be the same thing
No. Of course, both are addressable memory; but they are different concepts and as such neither merged nor interchangeable.