The basic example:
var b = 10;
var c = b;
b++;
console.log(b,c);
>> 11 10
c looks like a copy of b.
But in another case:
var x = {};
var y = x;
x.abc = 10;
console.log(x.abc, y.abc);
>> 10 10
Why is the y not a copy of x, but a reference which points to the same instance x points to?
Also, I guessed b++ creates another instance, so b points to the new instance but c points to the old one. However…
var u = 10;
setTimeout(function() {
console.log(u);
}, 10000)
u++;
>> 11
If u++ creates a new instance, then the u inside the anonymous function should point to the old u, shouldn’t it?
Both are references to the same immutable value.
xwas a reference to an object in the first place, soyis a copy of it (a copy of the reference, not a copy of the object).It doesn’t.
u++assigns a reference to 11 tou. The anonymous function is looking atuand not “the value ofuat the time the function was created”.