What's happened to arr?
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
Array.slice in JavaScript returns the shallow copy of the array. The start and end indices should be supplied to it as the first 2 parameters. The element at arr[start] is included in the copy, and the element at arr[end] is not.
Contrary to Array.splice, the original array won’t be modified when we use Array.slice.
So, after the first 2 lines of code, we’ll get the following state:
[ 1, 2, 3, 4, 5] // arr
[ 2 ] // slicedArr
Then, we do two actions under arr.splice:
- we remove 2 elements from
arrstarting atarr[1]. So the original array becomes is[ 1, 4, 5 ]at this point. - we destructure
…slicedArrand insert its elements intoarrstarting atarr[1]. This way we’ll get to our final state[ 1, 2, 4, 5]inarr.
Here’s a code snippet with additional logging:
const arr = [1, 2, 3, 4, 5];
const slicedArr = arr.slice(1, 2);
console.log(arr); // [ 1, 2, 3, 4, 5]
console.log(slicedArr); // [ 2 ]
arr.splice(1, 2, ...slicedArr);
console.log(arr); // [ 1, 2, 4, 5]
ANSWER: The original array arr will be modified and hold values [ 1, 2, 4, 5].

Top comments (0)