News for hackers. Stuff that matters.
Re:A Modern JavaScript Tutorial by bovermyer on Tuesday December 08, 2020 @09:50AM (#25345863)
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?

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)
Re:A Modern JavaScript Tutorial by rhengles on Tuesday December 08, 2020 @10:07AM (#25346113)
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.

[0] e.g. https://immutable-js.github.io/immutable-js/

Re:A Modern JavaScript Tutorial by ianjsikes on Tuesday December 08, 2020 @10:11AM (#25346167)
The cheaty way is `let copy = JSON.parse(JSON.stringify(val))`. Doesn't work for functions or cyclic structures though.