user3795437
user3795437

Reputation: 81

How to avoid binding object in JS?

I am not sure what's going on with this, probably I am doing something wrong, but to be honest, I cannot see what's the point. Just take a look at this code and see what happens:

var object = {
  one: "one",
  two: "two"
};

var object2 = {}

object2 = object;

object["three"] = "what?"

console.log(object2);

The output for the object2 should be {one: "one", "two": two"}, however it returns {one: "one", "two": two", "three": "what?"}

So why is this happening? I am not modifying object2, but it gets updated after the push of new value. How can I solve this? I just want to keep the object2 like before. Thanks

Upvotes: 0

Views: 226

Answers (2)

dankobgd
dankobgd

Reputation: 416

object2 references object (points to the same reference in memory)

i assume you want to create object2 that is a copy of the first one, which you can do like this:

var obj2 = Object.assign({}, object);

or

var obj2 = {...object}

you can check Object assign MDN, or just google about spread operator syntax

Upvotes: 4

Jagadish N
Jagadish N

Reputation: 29

When you assign object to object2, it is reference is given to object2. Hence when you add 'three':'what?' to object and print object2, it will be same.

Upvotes: -1

Related Questions