r/javascript • • May 28 '19

What are some JavaScript things beginners don't know?

333 Upvotes

383 comments sorted by

View all comments

5

u/pm_me_cute_rem_pics js/ux May 28 '19

that:

const catObject = {
    type: 'cat',
    attributes: {
        hasFur: true
    }
}

const copy = Object.assign({}, catObject)
// Or
const copy = { ...catObject }

will not create a copy of the nested object attributtes, it's still a reference to the original object. So changing the attributes object will change it for all copies.

example https://repl.it/repls/FloralwhiteGruesomeSystemcall

3

u/aragonix May 28 '19

Great response! Just wanted to add that one can JSON.parse(JSON.stringify(catObject)) to deep clone simple objects. Note that this method has its downsides: it will ignore all values that dont exist in JSON (functions etc.). Most of the time I would suggest lodash though.