Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign value not reference in javascript [duplicate]

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?

like image 695
Mubashar Abbas Avatar asked Oct 19 '16 14:10

Mubashar Abbas


People also ask

How do you copy an object without references?

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.

Is JavaScript copy by reference?

In JavaScript primitive types are copied and passed by value and objects are copied and passed by reference value.

Does JavaScript assign by reference or 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.


1 Answers

You can use Object.assign:

var fruit = {
   name: "Apple"
};

var vegetable = Object.assign({}, fruit);
vegetable.name = "potatoe";
console.log(fruit);
like image 186
BrTkCa Avatar answered Oct 12 '22 06:10

BrTkCa