How do primitive types in Object types be stored in JavaScript

Viewed 29

I read some files about the memory management of JavaScript (https://www.geeksforgeeks.org/memory-management-in-javascript/). I know that the primitive types are stored in the stack and object types are stored in the heap. But how about the primitive types in objects are stored in the memory? Are they also stored in the heap, or they are stored in the stack but their object has pointers pointed to them stored in the heap?

1 Answers

The ECMAScript Language Specification only specifies very little about Memory Management, the only two things it specifies are WeakRefs and FinalizationRegistry objects. Nothing else is specified, in particular, there is no mention of a heap nor of a stack.

If you search the specification for occurrences of the terms "heap" or "stack", you will find that the term "heap" appears zero times in the entire specification. The term "stack" appears 111 times, but only related to either the execution context stack or as an actual variable called stack in the description of an algorithm. (For example, both the serialization algorithm for JSON.stringify and several of the Module Linking algorithms use a variable of type List called stack in their cycle-detection algorithms.)

Note that this is quite normal: many Programming Language Specifications do not specify anything about Memory Management. (See the Scala Language Specification, the Java Language Specification, or the ISO/IEC 30170:2012 Information technology — Programming languages — Ruby specification.) In general, Programming Language Specifications try to specify only the minimum amount of constraints that are required for the user of a Programming Language to be confident in the results of their programs, but leave the language implementors as much freedom as possible.

Remember: everything that isn't specified is an opportunity for the implementor to create an optimization, i.e. to make your code run faster.

So, the simple answer to your question is: you don't know, you can't know, and you mustn't know. Every implementor is free to implement Memory Management in ECMAScript however they like.

For example, I believe the (now defunct) Parrot ECMAScript implementation for the (now defunct) Parrot VM did not use a stack. And I seem to recall seeing an ECMAScript implementation for small embedded microcontrollers that did not use a heap or a garbage collector. Both of these are perfectly compliant ECMAScript implementations, even though the latter one would crash if you created too many objects during the lifetime of your program.

Related