Last active
May 31, 2019 14:20
-
-
Save alex3165/a820e4ae1e293898b2f1f9037fb34f34 to your computer and use it in GitHub Desktop.
Javascript copy vs ref
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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