I am interested in why, in snippet B, y
is able to capture the value of x
after x
has been reassigned when the initialization of y
occurs before the reassignment of x
.
I have been told the reason is because, in snippet B, x
is a reference data-type - it's value is stored external from the variable/identifier and that variable/identifier just points towards the address of the external memory.
However I could still argue that at the specific 'time' when y
is being initialized, x
is still {5}
so y
should be {5}
. There must be something more for me to understand here - perhaps something to do with the order/timing at which JavaScript assigns value to variables...
A
x = 5;
y = x;
x = 6;
console.log(x);
console.log(y);
B
x = {one: 5};
y = x;
x.one = 6;
console.log(x);
console.log(y);