I am having a little problem assigning objects in javascript.
take a look at this sample code that reproduces my problem.
var fruit = {
name: "Apple"
};
var vegetable = fruit;
vegetable.name = "potatoe";
console.log(fruit);
it logs
Object {name: "potatoe"}
How can I assign the value not the reference of an object to another object?
const obj = {a:1,b:2,c:3}; const clone = {... obj}; console. log(clone); // {a:1,b:2,c:3}; Note: These above two methods are only used for shallow copying of objects but not for deep copying.
In JavaScript primitive types are copied and passed by value and objects are copied and passed by reference value.
The Bottom Line on JavaScript References On variable assignment, the scalar primitive values (Number, String, Boolean, undefined, null, Symbol) are assigned-by-value and compound values are assigned-by-reference. The references in JavaScript only point at contained values and NOT at other variables, or references.
You can use Object.assign:
var fruit = {
name: "Apple"
};
var vegetable = Object.assign({}, fruit);
vegetable.name = "potatoe";
console.log(fruit);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With