DEV Community

loading...
Cover image for JavaScript Interview Question #23: Array.splice

JavaScript Interview Question #23: Array.splice

coderslang profile image Coderslang: Become a Software Engineer Originally published at learn.coderslang.com on ・2 min read

js-test-23

How many times can you splice the array in JavaScript? What's the output?

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

Let’s start with the definition of splice.

The function splice is available in all JavaScript arrays and accepts the variable number of parameters. Here are 4 important things you should know about splice:

  • The first parameter is called start and represents the index of the first element that will be removed from the array.

  • The second argument is deleteCount. It determines the number of array elements that will be removed from the array

  • The third, the fourth argument, and so on, are the new elements that will be added to the array.

  • The function splice returns the array formed by deleted elements.

Now, we start the array arr with 5 elements [1, 2, 3, 4, 5].

The first splice extracts 2 elements starting from arr[1]. We immediately save them into the splicedArr.

Before the final splice we have the following state:

[ 1, 4, 5 ]  // arr
[ 2, 3 ]     // splicedArr
Enter fullscreen mode Exit fullscreen mode

The second splice once again removes 2 elements from arr starting at arr[1]. This leaves us with a single element — 1.

Then, we apply the destructuring with ... to the splicedArr and add elements 2 and 3 to the initial array arr.

Here’s the code snippet with 2 additional calls to console.log to help you understand the explanation better:

  const arr = [1, 2, 3, 4, 5];
  const splicedArr = arr.splice(1, 2);

  console.log(arr);         // [ 1, 4, 5 ]
  console.log(splicedArr);  // [ 2, 3 ]

  arr.splice(1, 2, ...splicedArr);
  console.log(arr);
Enter fullscreen mode Exit fullscreen mode

ANSWER: the array will eventually hold values [ 1, 2, 3 ] which will be logged to the console.

Learn Full Stack JavaScript

Discussion (2)

Collapse
pooriafaramarzian profile image
pooria-faramarzian

That's awesome man.
Please keep making stuff like this, many of us need it.

Forem Open with the Forem app