0

Why does the first function mutate originalArr (although I created copyArr to perform methods only on that copy)? And why doesn't the second function mutate originalArr?

function removeSmallest(originalArr) {
  const copyArr = originalArr;
  console.log(originalArr);
copyArr.splice(copyArr.indexOf(Math.min(...copyArr)), 1);
  console.log(originalArr); //here originalArr is mutated, why?//
  return copyArr;
}

function removeSmallest(originalArr) {
  const copyArr = [];
  copyArr.push(...originalArr);
  console.log(originalArr);
copyArr.splice(copyArr.indexOf(Math.min(...copyArr)), 1);
  console.log(originalArr); //originalArr not mutated, why?//
  return copyArr;
}

1 Answers1

0

JavaScript arrays work by reference, meaning that in the first function, both copyArr and originalArr point to the same object. To copy an array and avoid this, you can use the method you used in the second function, or simply use const copyArr = originalArr.slice().

Jotha
  • 418
  • 2
  • 7