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 Answer 1

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().

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.