0

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
C.Pr
  • 23
  • 2
  • variables are only references to a value, not a reference to a reference. – Daniel A. White Jun 17 '16 at 18:59
  • 3
    Possible duplicate of [Is JavaScript a pass-by-reference or pass-by-value language?](http://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language) – Claies Jun 17 '16 at 18:59
  • in particular, the answer http://stackoverflow.com/a/32793507/2495283 is very good, and shows examples with pictures. – Claies Jun 17 '16 at 19:01

4 Answers4

1

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?

Community
  • 1
  • 1
  • Thank you. This explanation was simple enough for my level and yet detailed just enough to keep me moving. – C.Pr Jun 17 '16 at 19:25
0

Because you haven't assigned it back. Its not by reference

Nafiul Islam
  • 1,220
  • 8
  • 20
0

In the simple case, what you are doing is assigning the value of a to b (assigning by value). You have not assigned b to always be the same as a (assigning by reference).

Javascript doesn't really support assigning by reference. There are some ways to achieve it, but that gets into the more complicated objects interactions you referred to in your question.

Chris G
  • 359
  • 2
  • 9
  • Yes thank you for this simple explanation to get me started. I was stuck and was unsure if what I was doing was 'assigning by value'. – C.Pr Jun 17 '16 at 19:06
0

This behavior is caused by the way Javascript sets variables.

Instead of setting b to be a reference to a, it grabs the value of a and sets b to that. You can do whatever you like to a and b will remain unchanged. If you want the behavior of b equaling whatever a is, just do b = a again, and it will equal a.

Imagine that you have a value that's constantly changing, like the time. You need to save what the value is at the moment, but keep the original intact. b = a. b is set to what a was at the time, but a continues to update without interruption.

MineAndCraft12
  • 671
  • 5
  • 15