Is this not the regular Array.splice method in JavaScript?

Tyav Moses
2 min readJun 10, 2021

At about 10 mins past 4 in the morning, she climbed down the stairs and boom!!! I knew there was a bug.

Using the right tool wrongly.

She must have spent a while trying to figure out what was her problem but still couldn’t. yet she was confident that it was correct because she copied it directly from MDN.

I looked at her code and it was syntactically correct to me.

“What is the problem with the code?” I asked.

“The array is supposed to be empty but it isn’t, looking at the logged value” She replied.

“I removed an item at the first index but it is not working, but this is the code I copied from MDN” She added.

Now here is the problem. Not that she didn’t read to the bottom of MDN’s article about Array.prototype.splice() because it was clear on MDN to me but she was…

Using the right thing from the right place for the wrong purpose which is as good as misunderstanding the tools you have.

First, let's see what the Array.splice(index, count[, ...items]) method does as a tool.

  1. The method mutates the Array when called. This means it changes the original array.
  2. The method removes a number of item(s) from the array starting and counting from the supplied index.
  3. If the index supplied is greater than the length, it inserts the new item(s) immediately after the last existing item of the array.
  4. The method inserts/replaces a number of item(s) supplied to it starting from the supplied index.
  5. The method returns an array of elements that have been removed from the original array.

Then, let’s understand what to look for and where to look for it.

  1. If I need to see the new value of my array after using the splice method, I would take a look at the original array. Remember I said it is mutated.
  2. If I need the elements that have been removed from the array, I would hold the return value of the splice method.

What was she doing wrong then?

As you must have guessed or known at this point that she is looking at the wrong value result instead of the original array ids .

Below are some examples:

The bottom line is to understand what you are trying to use well before copying it for use.

For further reading on Array.prototype.splice and other Array methods, you can visit MDN or javascript.info.

Thanks.

--

--