3 ms·
> Pass by value vs pass by reference - something that js programmers had to always understand in the past for the sake of handling primitives and objects in js.
by chakkepolja 5y ago
> Pass by value vs pass by reference - something that js programmers had to always understand in the past for the sake of handling primitives and objects in js.
Noob question. Aren't primitives immutable? Does it need distinguishing between Value & ref types?
- pornel 5y agoCompare: function(x) { x += 1; } function(o) { o.x += 1; } The first one behaves like passing by value, the second like passing by reference. Under the hood the `Number` x may have been passed by reference and changed by creating a copy, or it may have been JITed to be an i32 actually passed by value, or optimized out of existence entirely. How it is actually passed ends up being an implementation detail that you can't observe from high-level perspective.
- Byamarro 5y agoObjects are always treated as a reference, primitives as a value. To say they're immutable requires a bit more of a context - immutable in what sense? You can reassign a different value to a variable that stores a primitive, so it's not like variables that store them are immutable. I guess that the simpliest explanation would be by code: let x = 4 let z = x z = w // x is still 4 let x = { b: 3 } let z = x z.b = 2 // x is { b: 2 }, because x and z hold reference to the same object