At about 10 mins past 4 in the morning, she climbed down the stairs and boom!!! I knew there was a bug.
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.
- The method mutates the Array when called. This means it changes the original array.
- The method removes a number of item(s) from the array starting and counting from the supplied index.
- If the index supplied is greater than the length, it inserts the new item(s) immediately after the last existing item of the array.
- The method inserts/replaces a number of item(s) supplied to it starting from the supplied index.
- 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.
- If I need to see the new value of my array after using the
splicemethod, I would take a look at the original array. Remember I said it is mutated.
- If I need the elements that have been removed from the array, I would hold the return value of the
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
Below are some examples:
The bottom line is to understand what you are trying to use well before copying it for use.