C.Pr C.Pr - 5 months ago 6
Javascript Question

Explain in a simple way why second variable assigned to first variable doesn't update?

I want to learn more about what I just discovered when playing with variables. I think I found something called assigned by value or reference, but the examples on Stackoverflow are complicated using "objects", which I have not learned yet, so I am still unsure about below.

var a = 12;
var b = a;
a // 12
b // 12
a = 15;
a // 15
b //12

Answer

This is because you used assigned by value. var b is assigned to the value of var a (12).

var a = 12;
var b = a;
#b is only given the value of a
a #12
b #12
a = 15;
a #15
#Now here you assigned 'a' = 15, but 'b' is still 12
b //12

What you are thinking is assign by reference. For primitive variables (String, Number), Javascript does not allow assign by reference.

Assign by reference is that var b is a reference to var a. This means that if the value of var a changes, then the value of var b will change as well.

check out: Is JavaScript a pass-by-reference or pass-by-value language?

Comments