3 ms·
> In JavaScript, primitives are assigned/passed by value and not by reference. If you assign a primitive type's value to another variable, the value is copied -
by IshKebab 4y ago
> In JavaScript, primitives are assigned/passed by value and not by reference. If you assign a primitive type's value to another variable, the value is copied - not assigned a reference to the first variable (which is what happens for objects).
Bit off topic but is there actually any observable difference between primitives being value based vs being references to constants? Here's the example they give:
let num1 = 5;
let num2 = num1;
num1 = 6;
console.log({ num1, num2 }); // { num1: 6, num2: 5 }
But it's exactly the same for objects (e.g. arrays in this case):
let num1 = [5];
let num2 = num1;
num1 = [6];
console.log({ num1, num2 }); // { num1: [6], num2: [5] }
Definitely easier to think about them being value based and of course they are implemented like that but I don't think it's the only possibly interpretation.
- LunaSea 4y agoYou have to modify num1 to see the reference change. e.g: `num1[0] = 42` Your code is currently only reassigning a new value to the num1 variable.
- IshKebab 4y agoNo because I was talking about constants so you can't modify them. (Obviously you can literally modify them in the code I posted but it was just an illustration.)
- kevincox 4y agoThere is no difference between pass-by-reference and pass-by-value for immutable objects (unless there is a way to check object identity). So if you call the JavaScript primitive types Number, String, undefined, boolean, reference then all of them are immutable so there is no difference. Of course most people don't think of JS as passing a "reference primitive by value", they think about "passing an object by reference". Since all of the primitives are immutable it is probably then easier to think of JS as a pass-by-reference language from the semantic point of view. In fact if you really want to simplify you can imagine that every variable is just a reference to a value since it is equivalent.