DEV Community

Cover image for JavaScript Interview Question #29: Slice and dice
Coderslang: Become a Software Engineer
Coderslang: Become a Software Engineer

Posted on • Originally published at learn.coderslang.com on

JavaScript Interview Question #29: Slice and dice

js-test-29

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
Enter fullscreen mode Exit fullscreen mode

Then, we do two actions under arr.splice:

  • we remove 2 elements from arr starting at arr[1]. So the original array becomes is [ 1, 4, 5 ] at this point.
  • we destructure …slicedArr and insert its elements into arr starting at arr[1]. This way we’ll get to our final state [ 1, 2, 4, 5] in arr.

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]
Enter fullscreen mode Exit fullscreen mode

ANSWER: The original array arr will be modified and hold values [ 1, 2, 4, 5].

Learn Full-Stack JavaScript

Top comments (0)