Re:A Modern JavaScript Tutorial
by lighthazard on Tuesday December 08, 2020 @09:55AM
(#25345925)
You will need to clone the object somehow. The simplest solution is to go through each of the object properties and create a new object with those same properties (_.clone). Alternatively, recursively go through each property in the object and then keep going deeper through each property that is an object until you get a copy of everything to assign to a new object (_.deepClone)
I think the only reasonable thing that js can do here is what it does - copy the reference. Also, there is a simple way to copy all properties from a object: const copy = { ...object }; Of course, if these properties are themselves objects, then changes in one of them will appear in the other.
One way to have a deep copy which shares nothing is const copy = JSON.parse(JSON.stringify(object)); but that may not always work. In short, copying a arbitrarily large object will probably waste memory, so it should be a little hard so you don't do it unless it's really necessary.
Re:A Modern JavaScript Tutorial
by derivagral on Tuesday December 08, 2020 @10:20AM
(#25346288)
In addition to the cloning stuff, I've seen use of an immutables library [0] to make this stuff a little more explicit and simple. Not sure if that's still fashionable though.
As someone who doesn't use Javascript much... is there a way to force it to copy the current state of the original variable to the new variable, without it being a reference and without having to use something like lodash?