0

The title might seems weird, but I don't really know how to describe this situation as I'm a beginner in JavaScript.

Here's the code :

a={};
var b=a;
b['a']='x';
console.log(a);

the result will be:

Object { a="x"}

shouldn't it be a blank object because I set 'x' to variable b only ?

Edxz
  • 823
  • 2
  • 7
  • 22

2 Answers2

7

a contains a reference to an object, like this:

+-----+        +--------------+
|  a  |------->| (the object) |
+-----+        +--------------+

So when you do:

var b = a;

Now you have two variables referring to the same object.

+-----+
|  a  |---+
+-----+   |    +--------------+
          +--->| (the object) |
+-----+   |    +--------------+
|  b  |---+
+-----+

So naturally, any changes you make to that object (adding a property to it, in your case) are visible through either reference.

T.J. Crowder
  • 959,406
  • 173
  • 1,780
  • 1,769
0

b is a reference to a so that is a normal behavior. To avoid that you need to make a clone. For example, using jQuery framework you could simple do: var b = $.extend(true, {}, a};

letiagoalves
  • 10,994
  • 4
  • 38
  • 66