1

I am sure there is an explanation for this but I cannot find it. The phenomenon I am facing is this:

const options = {"from":"0xa4cxxx","gasPrice":"0x2dc6c0","gas":"0x2dc6c0"};

let asd = options;
asd.from = "ZMY";

console.log("asd", asd);
console.log("options", options)

Prints:

asd {from: "ZMY", gasPrice: "0x2dc6c0", gas: "0x2dc6c0"}
options {from: "ZMY", gasPrice: "0x2dc6c0", gas: "0x2dc6c0"}

I am confused as to why this is changing the const variable too. What is the best way to change asd without changing the original const options and why this is happening?

blockbyblock
  • 115
  • 5
  • 1
    objects, arrays and classes are reference types, which means, they don't pass only the value, but the reference in the memory to it. So it doesn't matter where do you make changes, if it's a reference type, it will change in every variable that points to that reference. – kmp Dec 07 '20 at 10:51
  • yes @Reyno it does – blockbyblock Dec 07 '20 at 10:53

1 Answers1

2

You only have one objects, but two references to it. If you want to do a (shallow) clone of the options object instead of referring to it, you can do

const options = {"from":"0xa4cxxx","gasPrice":"0x2dc6c0","gas":"0x2dc6c0"};

let asd = {...options};
asd.from = "ZMY";

console.log("asd", asd);
console.log("options", options)
Jkarttunen
  • 6,764
  • 4
  • 27
  • 29
  • Thank you, its working. Could you explain what the {...options} does, or provide a link please? – blockbyblock Dec 07 '20 at 10:51
  • it is a spread operator. it creates a new object, {}, and assigns the properties of options object to the new object. You can read more here: https://codeburst.io/a-simple-guide-to-destructuring-and-es6-spread-operator-e02212af5831 – Jkarttunen Dec 07 '20 at 10:52
  • found it here https://stackoverflow.com/questions/29050004/modifying-a-copy-of-a-javascript-object-is-causing-the-original-object-to-change – blockbyblock Dec 07 '20 at 10:53