2

I have seen this question being asked multiple times but I have a specific example to clarify.

var a = {animal: 'cat'};

var b = a;

a.animal = 'bear';

Here, I see b.animal will give an output "bear". Why is that? And how do I retain the original reference "cat" for variable b?

Dinesh
  • 73
  • 4
  • 10
  • 4
    You have copied a *reference* from `a` to `b`, but they both point *at the same object*. If you want to copy the object, then you need to copy each property of that object to a new object. – Matt Burland Mar 04 '14 at 16:14
  • 1
    Take a look at this question: http://stackoverflow.com/q/122102/522479 – Cobra_Fast Mar 04 '14 at 16:15
  • 3
    It's by-value, but the value is an object reference. So, `b` is a copy of `a`, but they both still refer to the same object. [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) – Jonathan Lonowski Mar 04 '14 at 16:16
  • 1
    Javascript is always pass by value...1000 % sure – Deepak Ingole Mar 04 '14 at 16:17
  • 1
    @Pilot and for an object the value is its reference. – Ben Thurley Mar 04 '14 at 16:20

3 Answers3

2

Yes, both refer to the same object.

May be you are confused because in Javascript, you usually don't use the "new" keyword on built-in types, even if you can.

You could also declare "a" like this :

var a = new Object();
a.animal = "cat";

Now it is maybe more clear why "b" change when "a" change.

If you "b" have its own property then you have to clone "a".

Community
  • 1
  • 1
bdavidxyz
  • 2,492
  • 1
  • 20
  • 40
1

You should clone the object instead of copying the reference (b = a);

here's a question where this problem is very well explained: How do I correctly clone a JavaScript object?

Community
  • 1
  • 1
Hoijof
  • 1,343
  • 15
  • 27
1

'Primitives' are copied, objects are not (that is, the reference to it is copied). If you need to protect the property, define it writeable:false via defineProperty

nullpotent
  • 9,162
  • 1
  • 31
  • 42