r/javascript • u/cryptomallu123 • 7d ago
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
-1
7
u/theScottyJam 7d ago
I actually feel like this is an anti-helpful way to understand JavaScript data.
It starts with this quote:
The real answer is simple - primitives are immutable, they can't be modified. If you freeze an object, you'll find that it behaves exactly the same as a primitive in this regard, but making an object frozen doesn't move it onto the stack instead of the heap or anything.
A better mental model is to assume that all values, primitives and objects, are handled like references. You pass a string into a function, and the function receives a reference to the exact same string. Primitives have no special treatment. Of course, under the hood, an engine might copy primitives instead of passing references to them around, but that's an implementation detail that shouldn't effect your mental model of the language, and it's a detail that may change between engines. For example, I'm sure if you pass around a large string, the engines aren't constantly duplicating those - why should they, they're immutable.