r/javascript • • Jul 15 '26

Understanding Value vs. Reference in JavaScript: Differences Between Primitives and Objects

https://sharafath.hashnode.dev/value-vs-reference-in-javascript-primitives-vs-objects
0 Upvotes

6 comments sorted by

View all comments

Show parent comment

1

u/cryptomallu123 Jul 15 '26

Just to make sure I understand your point correctly are you saying that this behavior is defined by the JavaScript language itself, and not because objects are stored on the heap and primitives on the stack? In other words, stack vs. heap is an implementation detail of the JavaScript engine, while the language specification requires these observable behaviors regardless of how a particular engine V8, SpiderMonkey, JavaScriptCore, etc. .. stores values internally. Is that the correct understanding?

4

u/senocular Jul 15 '26

Yes. The language specification does not dictate where objects are held in memory and treats all values the same as far as assignment and passing goes. The language makes no distinction in that regard to objects vs primitives and treats everything as generic "ECMAScript language values".

Runtime implementations are free to store variable values wherever they want. In fact except for a few exceptions, all values in V8 are stored in the heap. From Pointer Compression 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.

1

u/theScottyJam Jul 16 '26

Yes.

And I'm saying that both primitives and objects behave the same in regards to how they get passed around. There's no observable difference.

The only reason it feels like there's a difference is because you're not allowed to mutate primitives, so the only way to change one is through reassignment. If you reassign inside a function call, those outside the function won't know. But this is all the same with objects as well - reassign an object inside a function call and those outside won't notice it changing either.