Assign value not reference in javascript

Mubashar Abbas picture Mubashar Abbas · Oct 19, 2016 · Viewed 25.8k times · Source

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?

Answer

BrTkCa picture BrTkCa · Oct 19, 2016

You can use Object.assign:

var fruit = {
   name: "Apple"
};

var vegetable = Object.assign({}, fruit);
vegetable.name = "potatoe";
console.log(fruit);