1

Does the heap only contain pointers? And the stack is the place where the actual data resides?

Pointers on the heap section point to, either other pointers in the heap, or they point to the values stored in the stack section of the memory.

Is it true?

0

1 Answer 1

1

From this documentation:

Stack:

A stack is a data structure that JavaScript uses to store static data. Static data is data where the engine knows the size at compile time. In JavaScript, this includes primitive values (strings, numbers, booleans, undefined, and null) and references, which point to objects and functions.

Heap:

The heap is a different space for storing data where JavaScript stores objects and functions.

Coming to your question: Does the heap only contain pointers?

No, JS doesn't have pointers. You can consider objects are pointers in JS.

Unlike in C, you can't see the actual address of the pointer nor the actual value of the pointer, you can only dereference it (get the value at the address it points to.)

From this, here is a nice example with explanation:

//this will make object1 point to the memory location that object2 is pointing at
object1 = object2;

//this will make object2 point to the memory location that object1 is pointing at 
function myfunc(object2){}
myfunc(object1);

Let me know if it helps.

Sign up to request clarification or add additional context in comments.

15 Comments

Thank you for your response. By pointer I meant an address in the memory that holds not a value but another address.
@Slev7n - you can say references as address. The stack contains a reference to the object in the heap. You can find more details in this guidance link. Let me know if it helps you? :)
@Slev7n You should consider that everything in JS is stored on the heap, minus those things that the engine can optimise to put on the stack (because they don't outlive the call) or in registers (because they are entirely temporary).
@Rajendraarora "Static data is data where the engine knows the size at compile time." - this is a weird definition that you quoted (?) from the article. Static means non-changing, and "static data" usually refers to constants etc. Not to statically-sized data. "A stack is a data structure that JavaScript uses to store static data." - this is quite wrong. It's neither specific to JavaScript nor is all statically-sized data stored on the stack nor can only statically-sized data be stored on the stack. The article you link doesn't even describe the relevant core principle of a stack.
@tweekz The ECMAScript specifications says nothing about where to allocate memory. It doesn't even say a lot about garbage collection.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.