let arr1=[1,2,3,4];
let arr2=arr1;
arr2.splice(1,3,5,6,7);
console.log(arr1);
arr1 gets spliced exactly the same as arr2 - why does this happen?
I know that splice changes the original array but I would think that its original array in this case is arr2 and not arr1…
Because arr1 is an array of literal values (boolean, number, or string), you can use any deep copy technique discussed above, where the spread operator ... has the highest performance.
// Highest performance for deep copying literal values
arr2 = [...arr1];
// Any of these techniques will deep copy literal values as well,
// but with lower performance.
arr2 = arr1.slice();
arr2 = arr1.splice(0);
arr2 = arr1.concat();
arr2 = JSON.parse(JSON.stringify(arr1));
arr2 = $.extend(true, [], arr1); // jQuery.js needed
arr2 = _.extend(arr1); // Underscore.js needed
arr2 = _.cloneDeep(arr1); // Lo-dash.js needed
arr2 = copy(arr1); // Custom-function needed - as provided above
This article does a great job of answering. You are experiencing one bummer about javascript. Arrays pass by reference not by value. Meaning that arr1 and arr2 were pointing at the same value. It is a big reason people have come up with ways to enforce immutable data so you don’t have unintended side effects like what you are experiencing.