In YDKJS types and grammar, the author stated there are two ways of passing values in js. One is value passing (when variable holds a primitive type of value) the other one is reference passing. (when variable holds an object).
Here are two code snippets:
var a = 2; var b = a; // `b` is always a copy of the value in `a` b++; a; // 2 b; // 3 var c = [1,2,3]; var d = c; // `d` is a reference to the shared `[1,2,3]` value d.push( 4 ); c; // [1,2,3,4] d; // [1,2,3,4]
var a = [1,2,3]; var b = a; a; // [1,2,3] b; // [1,2,3] // later b = [4,5,6]; a; // [1,2,3] b; // [4,5,6]
Can I understand it as
- in the 1st snippet, what we did was changing the value of the primitive value itself. (by adding 4 to the end of it), therefore after the value changed, all of the references changed as well.
- in the 2nd snippet, we did not change the primitive value at all, we just assigned
bto point to another reference value which is [4,5,6].
Also are these understandings correct?
- Primitive values are like the parent of all its references.
- In js primitive value cannot be touched. cannot be altered.
- so we change its references instead.
- there is no direct link between references.
- but there is a link between reference and its parent: primitive value
- if you change the value of reference, its primitive parent will be changed as well and vice versa.