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?

5
  • 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. Commented Mar 4, 2014 at 16:14
  • 1
    Take a look at this question: stackoverflow.com/q/122102/522479 Commented Mar 4, 2014 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? Commented Mar 4, 2014 at 16:16
  • 1
    Javascript is always pass by value...1000 % sure Commented Mar 4, 2014 at 16:17
  • 1
    @Pilot and for an object the value is its reference. Commented Mar 4, 2014 at 16:20

3 Answers 3

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".

Sign up to request clarification or add additional context in comments.

Comments

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?

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.