Normally when you pass Arrays around in JavaScript and in every other language they are passed by reference. That is a sane default, but sometimes you want to use or make a copy, so that original is not modified when we do changes.
Here is how by-reference work :
a = [1,2,3,4,5] b = a b[2] = 55 console.log(a) ------ [ 1, 2, 55, 4, 5 ]
… changing b changes a too.
But if we copy the array a stays the same.
Below I present two ways to copy Arrays in JavaScript via slicing or using the splat/triple-dot-operator.
a = [1,2,3,4,5,[6,[7],8],9] b = a.slice() b[2] = 55 console.log('slice-copy : ') console.log(a) a = [1,2,3,4,5,[6,[7],8],9] b = new Array(...a) b[2] = 55 console.log('... copy : ') console.log(a) ----- slice-copy : [ 1, 2, 3, 4, 5, [ 6, [ 7 ], 8 ], 9 ] ... copy : [ 1, 2, 3, 4, 5, [ 6, [ 7 ], 8 ], 9 ]
This also works for objects/hashes
a = { 'key1' : 'val1', 'key2' : 'val2' }
b = a //reference
b['key1'] = 'val55'
console.log(a)
a = { 'key1' : 'val1', 'key2' : 'val2' }
b = { ... a } //copy
b['key1'] = 'val55'
console.log(a)
-----
{ key1: 'val55', key2: 'val2' }
{ key1: 'val1', key2: 'val2' }