I have a few questions about setting a variable equal to another variable in JavaScript.
Let's say we create an object, a
and set b = a
.
var a = {
fname: Jon,
lname: Smith,
age: 50
}
var b = a;
I understand that if we change one of a
's properties b
will also be changed because when we set b = a
we don't clone a
's data, but rather create a reference to a
's data. For example if we set a.fname = Sarah
, the new value of b.fname
will be Sarah
.
If we try to clear a
though by setting a = {}
, object b
will remain unchanged. I don't understand why manipulating an object in this way produces a different result than in the 1st example.
Also I have a question about the following scenario.
var x = 10;
var z = x;
If we then set x = 20
, the value of z
remains unchanged. Based on the behavior described in my 1st question, one would think that the new value of z
would reflect the new value of x
. Could someone please explain what I am missing here?
Thank You!