Effects of splice()

In this section of code:

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…

In this case, arr1 and arr2 are the same array. You’d need to copy the array to prevent this.

So when assigning one array to another they become one?

So should I just slice() for this kind of thing or is there a better way to copy the array?

There is a lot of good discussion here.

Specifically

Answer

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.

https://www.dyn-web.com/javascript/arrays/value-vs-reference.php

I wouldn’t call it a bummer. Passing arrays by value has a serious performance impact. If your arrays are not tiny, you want pass by reference.

1 Like