Skip to content

Instantly share code, notes, and snippets.

@alex3165
Last active May 31, 2019 14:20
Show Gist options
  • Save alex3165/a820e4ae1e293898b2f1f9037fb34f34 to your computer and use it in GitHub Desktop.
Save alex3165/a820e4ae1e293898b2f1f9037fb34f34 to your computer and use it in GitHub Desktop.
Javascript copy vs ref
const a = { byId: {} }
// b is a reference to a, any change on a will mutate b
const b = a
// c is shallow copy of a, any change on the top level properties of a will not affect c although any change of nested object would affect c, if we mutate byId in a it will update byId in c
const c = { ...a }
//or
const cprime = Object.assign({}, a)
// d is a deep copy of a, any change in a wont affect d.
const d = JSON.parse(JSON.stringify(a))
// There are nicer way to deeply copy an object, for example one could use Lodash deepClone operator.
// With lodash
const e = _.deepClone(a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment