# Removing and Adding items to the List

So I just started learning Coding 101 Introduction course, and I don’t understand the philosophy behind the “adding or removing items from list”

myList = ['apple', 'banana', 'pear'] myList.splice(1, 1) // removes 'banana' from myList and returns 'banana' // now, myList == ['apple', 'pear']

and

myList = ['apple', 'banana', 'pear'] myList.splice(1, 0, 'mango') // make 'mango' the second item in the list // now, myList = ['apple', 'mango', 'banana', 'pear']

So if I want to put mango to the second item on the list, why do we use "1 and 0 and " mango "?
And when we remove bananas, why did we put 1,1 twice?

Thanks.

The documentation for the Array.splice() method might be helpful in understanding this, but I’ll summarise for you as well.

Let’s consider the first situation, where we are removing `banana` from the list.

``````myList = ['apple', 'banana', 'pear'];
myList.splice(1, 1);
``````

Here, we are using the form of the method which takes two arguments: `.splice(start, deleteCount)`.

In this form, the `start` argument tells the `.splice` method where in the array we want to start affecting the member elements. In this case, `1` selects the second element in the array - `banana`. The `deleteCount` argument tells `.splice` how many elements we wish to remove, so again in this case we’re telling it to remove `1` element.

The end result? `.splice` removes one element from the array, `banana`, and you’re left with `['apple', 'pear']`.

Let’s now consider the second situation, where you are adding `mango` to the list.

``````myList = ['apple', 'banana', 'pear'];
myList.splice(1, 0, 'mango');
``````

Here we are using the form of the method which takes multiple arguments: `.splice(start, deleteCount, item1, item2, ...itemN)`.

In this form, like before, the `start` argument tells the method where we want to start making changes, and we again are telling it to start at index `1` - `banana`.

The second argument, similarly, is `deleteCount` only this time we’re passing the value `0` and so telling the method that we don’t want to delete anything.

The third (though you can provide many more) argument, `item1`, is a new element which you want to add to the list at the `start` index. We’re providing the string value `mango`, so the array becomes `['apple', 'mango', 'banana', 'pear']` because `mango` has been inserted to the array at index `1`.

Hope that helps.

3 Likes

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.