javascriptvariables

Does assigning a variable to another variable track changes made to the source variable?


I'm having difficulties understanding the swapping of variables. There are many helpful threads explaining how to actually do it, but I am having difficulties understanding it. The example I'm talking about is:

var a = 1;
    b = 2;
    c = a;
a = b;
b = c;

In my (very basic) understanding I read that in plain english as: the variable c per declaration holds whatever the variable a is pointing at. Since we assign a = b after the declaration, shouldn't the next assignment make b hold the value 2 (because c is pointing at a which we just assigned to b)?


Solution

  • JavaScript is call/assign by value (more specifically, call/assign by sharing) I.e. when you assign a variable to another variable, the value of the variable is copied. Assigning a new value to a variable never changes the value of another variable. There is no implicit link between them.

    A bit more visual: Assuming that b holds the value v, then after a = b, we have

    b -> v
    a -> v
    

    You seem to think that we have a -> b -> v instead, which is not the case.

    In your example:

    c = a; // c now holds the value 1
    a = b; // a now holds the value 2
    b = c; // b now holds the value 1