Skip to content

Instantly share code, notes, and snippets.

@ianfinch
Last active July 8, 2022 07:31
Show Gist options
  • Save ianfinch/b2ea347e752d3780fb1afa8eabf8694e to your computer and use it in GitHub Desktop.
Save ianfinch/b2ea347e752d3780fb1afa8eabf8694e to your computer and use it in GitHub Desktop.
Example of Javascript pass by value side effects
// Function to change the passed in variable
testFn0 = obj => { obj = {}; }
// Function to change level one variable
testFn1 = obj => { obj.b = 999; }
// Function to change level two variable
testFn2 = obj => { obj.b.b = 999; }
// Directly changing the passed in variable should not affect it
x = { a: 1, b: 2, c: 3 }
testFn0(x)
console.log(x) // result: { a: 1, b: 2, c: 3 }
// Changing a level one variable will produce a side effect
testFn1(x)
console.log(x) // result: { a: 1, b: 999, c: 3 }
// To avoid this we can pass in a copy
x = { a: 1, b: 2, c: 3 }
testFn1( Object.assign({}, x) )
console.log(x) // result: { a: 1, b: 2, c: 3 }
// But because Object.assign() is a shallow copy,
// at level two there will still be a side effect
x = { a: 1, b: { a: 1, b: 2, c: 3 }, c: 3 }
testFn2( Object.assign({}, x) )
console.log(x) // result: { a: 1, b: { a: 1, b: 999, c: 3 }, c: 3 }
// To be completely protected, need to use a deep copy.
// There's not a built-in Javascript function for this,
// but various libraries provide this. To keep this simple,
// I'll just use the stringify/parse hack.
x = { a: 1, b: { a: 1, b: 2, c: 3 }, c: 3 }
testFn2 ( JSON.parse(JSON.stringify(x)) )
console.log(x) // result: { a: 1, b: { a: 1, b: 2, c: 3 }, c: 3 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment