Slice is copy. What is '=' for?

Hello there! I’m wondering why my arr2 is mutated if I just trying to copy arr2 value to arr3?

function frankenSplice(arr1, arr2, n) {
  let arr3 = arr2; //here
  for (let i = 0; i < arr1.length; i++){
    arr3.splice(n, 0, arr1[i]);
    n++;
  }
  return arr3;
}

frankenSplice([1, 2, 3], [0, 4, 5], 1);

ERROR:
The second array should remain the same after the function runs.

PS console.log shows no changes. why?

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/slice-and-splice/

In JavaScript, you can not copy non-primitives (objects) by assignment as you are able to do with primitives, as the values of non-primitives are held by by reference.
For Primitives this would work

const primitve = 'Hello'
let primitiveCopy = primitve 
console.log(primitve) // Hello
primitiveCopy = 'World'
console.log(primitve) // Hello (stays same)

However for an array

let arr = ['A','B','C']
let arrCopy = arr; 
console.log(arr) //[ 'A', 'B', 'C' ]
arrCopy[0] ='D';
console.log(arr) // [ 'D', 'B', 'C' ] Original Array mutated !!

3 ways that you can avoid the mutation of arrays

//1 slice
arr = ['A','B','C']
arrCopy = arr.slice()
arrCopy[0] = 'D'
console.log(arr) // [ 'A', 'B', 'C' ]

//2 spread
arr = ['A','B','C']
arrCopy = [...arr]
arrCopy[0] = 'D'
console.log(arr) // [ 'A', 'B', 'C' ]

//3 concat
arr = ['A','B','C']
arrCopy = [].concat(arr)
arrCopy[0] = 'D'
console.log(arr) // [ 'A', 'B', 'C' ]

Note, if you have an array of objects, some of the objects properties may still be mutated even with the above 3 ways, need to be careful…

2 Likes