News for hackers. Stuff that matters.
Re:Deep Cloning Objects in JavaScript, the Modern Way by lambda_garden on Friday December 22, 2023 @06:17AM (#38733122)
I use React.

Why does that require deep clones?

I simply do:

    return {
      ...current
      foo: "bar"
    };
Re:Deep Cloning Objects in JavaScript, the Modern Way by VPenkov on Friday December 22, 2023 @07:03AM (#38733349)
I'm not sure if you're asking why deep copies are useful or something else.

Maybe you're handing over your data to a library developed by someone else and you want to make sure the library cannot mutate your original data, so you opt to pass a deep copy instead. Or maybe you are the author of said library and you want to make sure you preserve the original data so you copy it on input rather than on output.

There are many situations where deep-copying is useful but I agree that you should use the simplest pattern that works for your use-case.

Re:Deep Cloning Objects in JavaScript, the Modern Way by Drakim on Friday December 22, 2023 @07:45AM (#38733590)
if "current" is a deep object here and contains other objects/arrays, you risk that wherever you are sending this shallow copy will mutate those deeper values and potentially mess things up for the code where "current" came from.

Maybe it's not a situation that comes up often, but it would be fairly hard to debug and guarding yourself against mysterious problems in advance is always neat.

Re:Deep Cloning Objects in JavaScript, the Modern Way by lambda_garden on Friday December 22, 2023 @07:49AM (#38733614)
In practice, I think it's easier to use linting and type-systems to prevent other code from mutating you stuff than defensive copying.
Re:Deep Cloning Objects in JavaScript, the Modern Way by VPenkov on Friday December 22, 2023 @08:38AM (#38734004)
You could make the same argument backwards though - many people may find it easier to do deep copies rather than throwing extra software they might not necessarily be familiar with.