Question

When you assign a primitive-type such as a number, string, or boolean to a variable in JavaScript (or any language for that matter) it opens up a slot in memory, places it in, and puts a label on it to be referenced later, correct?

var a = 1;
var b = 'foobar';
var c = false;
var d;

// What our memory would happen to look like:
var_a => 0x00 [1         ]
var_b => 0x01 ["foobar"  ]
var_c => 0x02 [false     ]
var_d => 0x03 [undefined ]

Now here is my question, how are composite-types such as arrays, functions, or objects stored in memory? I heard that objects are created somewhere off in memory and the variable only contains a reference address to this object. How is that possible? From the memory table I typed out above it seems like memory tables can only contain a single value.

Is there like special slots in memory for composite-types? Are arrays and functions stored the same way as objects (eg by reference)?

Was it helpful?

Solution

objects are created somewhere off in memory and the variable only contains a reference address to this object.

Yes.

How is that possible? From the memory table I typed out above it seems like memory tables can only contain a single value.

A reference address (called a "pointer") is a single value.

Is there like special slots in memory for composite-types?

Yes. Composites, also called "struct"s, can contain multiple values (but a fixed amout of them), like "a string for the name, a reference to the next property, and a field for the value" for a single link when describing an object as a linked list. The high-level JavaScript objects are stored as a multitude of different structures joined together to represent the data.

Are arrays and functions stored the same way as objects (eg by reference)?

Yes. However, their data structures differ, they're optimized on different things.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top