EN
JavaScript - modifying object copy causes the original object change
1 answers
0 points
Why is modifying copy of an object causing the original object change?
My code:
xxxxxxxxxx
1
const object1 = { a: 1 };
2
const object2 = object1;
3
4
object2.a = 2;
5
6
console.log(object1.a); // 2 instead of 1
1 answer
0 points
You've misunderstood the statement: var object2 = object1
.
In JavaScript, objects are passed and assigned by reference, so object1
and object2
are references pointing to the same object.
Solution
To avoid it, you can create a copy of the object:
xxxxxxxxxx
1
const object2 = Object.assign({}, object1);
Full example:
xxxxxxxxxx
1
const object1 = { a: 1 };
2
const object2 = Object.assign({}, object1);
3
4
object2.a = 2;
5
6
console.log(object1.a); // 1
7
console.log(object2.a); // 2
See also
References
0 commentsShow commentsAdd comment