denysdovhan / wtfjs

🤪 A list of funny and tricky JavaScript examples
http://bit.ly/wtfjavascript
Do What The F*ck You Want To Public License
34.75k stars 2.55k forks source link

New object references the same old one in memory #222

Closed Dectom closed 2 years ago

Dectom commented 2 years ago

https://javascript.info/object-copy

If you want to 'copy' or duplicate an object you can't just use let new = old; because this creates a memory reference to the existing object so any changes made on new impact the old.

This trips up a lot of new devs and is a fucky part of JS so you can use the clone as shown on the linked guide, or you can do something like this let new = JSON.parse(JSON.stringify(old)); to create a new copy of the original object

denysdovhan commented 2 years ago

Yeah, that might not be obvious for beginners. However, this doesn't seem to be a good example (in my opinion). It's something that every js dev should know in order to write useful code.