-1

I want to understand this concept which confuses me.

suppose I have the below logic:

function test(){
    var jsonObj_1 = {};
    var jsonObj_2 = {};
    
    jsonObj_2 = jsonObj_1;
    jsonObj_2.myKey = 3;

    console.log(jsonObj_2) // result => {myKey:3}
    console.log(jsonObj_1) // result => {myKey:3}

}

my question is why jsonObj_1 is equal to {myKey:3} when it's never get assigned?!

2
  • 2
    Objects are represented as references. When you assign an object value to another variable, you do not make a copy of the object: you assign a shared reference to the same object. Commented Nov 17, 2020 at 18:17
  • @Pointy Thank you for the explanation Commented Nov 17, 2020 at 18:19

4 Answers 4

5

you are assigning the ref of jsonObj_1 in jsonObj_2. In simple words the address of the first variable. I would suggest you to read some docs on call by reference and call by value.

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

Comments

1

When the non-primitive variables are assigned using "=", the reference will also be copied. This may lead to the mutation for all the variables that a particular object is assigned to.

Try the following.

You can use JSON.stringify to convert it to string and then parse into JSON.parse.

jsonObj_2= JSON.parse(JSON.stringify(jsonObj_1));

You can use spread operator.

jsonObj_2 = {...jsonObj_1}

Comments

1

What you will need is Object.assign

const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };

const returnedTarget = Object.assign(target, source);

console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }

console.log(returnedTarget);
// expected output: Object { a: 1, b: 4, c: 5 }

Example here: https://googlechrome.github.io/samples/object-assign-es6/

Comments

1

JavaScript Objects are Mutable. They are addressed by reference, not by value.

If jsonObj_1 is an object, the following statement will not create a copy of jsonObj_1:

var jsonObj_2 = jsonObj_1 ;  // This will not create a copy of jsonObj_1.

The object jsonObj_2 is not a copy of jsonObj_1 . It is jsonObj_1. Both jsonObj_2 and jsonObj_1 are the same object.

Any changes to jsonObj_2 will also change jsonObj_1, because jsonObj_2 and jsonObj_1 are the same object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.