Are JS primitives references?

73 Views Asked by At

I have found explanations that primitives and references get stored directly on the stack (static memory - size of the values is known), whereas objects, functions, etc get allocated on the heap (dynamic memory - to be able to grow).

Source: https://felixgerschau.com/javascript-memory-management/

Now I've read a few articles where the wording suggests that everything in JS is accessed by reference.

https://daveceddia.com/javascript-references/

So this would mean that primitives are also stored as reference. Is any value stored directly on the stack after all? Another indication is that if you write something like

// no prior variable definition
console.log(a);
// ReferenceError: a is not defined

it will actually give you a ReferenceError, although it could be any type (including primitives).

So, it seems to me like everything in JS is a reference. Is that correct? If yes - where is a referenced primitive value stored? On the heap? On the stack (as it is a primitive)? Can a reference point to the stack?

1

There are 1 best solutions below

0
tweekz On

I want to share the results of my research in case someone else finds it interesting as well.

While the ECMA specification does not seem to be specific (it is also hard to read from a users point of view), there is plenty of information how V8 (Chromium / NodeJS) handles this matter:

It basically puts everything on the heap and references it with a pointer, except for small integers. Small integers are baked into the pointer with a technique called pointer tagging (encoded in the last bits).

Here's what the V8 developer blog says about this topic:

https://v8.dev/blog/pointer-compression#value-tagging-in-v8

JavaScript values in V8 are represented as objects and allocated on the V8 heap, no matter if they are objects, arrays, numbers or strings. This allows us to represent any value as a pointer to an object.

Many JavaScript programs perform calculations on integer values, such as incrementing an index in a loop. To avoid us having to allocate a new number object each time an integer is incremented, V8 uses the well-known pointer tagging technique to store additional or alternative data in V8 heap pointers.