1

Why is it that when I assign a variable to an object and make a change to that variable it also changed the objects? For example:

c = 26;
a = b = c;
a += 1;

a      // 27
b      // 26
c      // 26

but

z = {};
x = y = z;
x.ab = 5; 

x      // Object {ab: 5}
y      // Object {ab: 5}
z      // Object {ab: 5}

Why (in the example above) does y.ab and z.ab exist? I only modified x not y or z. Howcome in the first example (with the integers), when I changed the value of a, b and c weren't affected?

Bentley Carr
  • 672
  • 1
  • 8
  • 24

1 Answers1

2

When you assign an object to a variable, it just makes a reference to the original object, it doesn't make a copy. So all the variables refer to the same object.

Barmar
  • 741,623
  • 53
  • 500
  • 612