3 ms·
This is great. However, it gives the example of copying a variable by assigning another variable to it. This doesn't copy a variable's contents - it makes the n
by bovermyer 6y ago
This is great. However, it gives the example of copying a variable by assigning another variable to it. This doesn't copy a variable's contents - it makes the new variable a pointer to the original variable.
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?
- lighthazard 6y agoYou 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)
- rhengles 6y agoI 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.
- ianjsikes 6y agoThe cheaty way is `let copy = JSON.parse(JSON.stringify(val))`. Doesn't work for functions or cyclic structures though.
- derivagral 6y agoIn 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. [0] e.g. https://immutable-js.github.io/immutable-js/ https://immutable-js.github.io/immutable-js/