FAQ: Lists - Adding Items to a List

Hello, @tcart38.

Welcome to the forums.

At this point, it isn’t really important to understand exactly how the Array.splice() method works, but since you asked, I’ll try to explain.

First of all, Array.splice() is a JavaScript method. You can read about it in the official MDN Docs, and even practice with it yourself here.

This method takes one required argument, and can also take additional optional arguments. Arguments are the values separated by commas between the ( ). The first argument in the example is 1. That is the index where we wish to make a change to the array (referred to as list in the exercise). The second argument is 0. This is the number of array elements that we want to remove. Since we don’t want to remove any, the value is 0. The third argument is 'mango', so 'mango' will be added to the array at index 1. If we change these values, we can change the array differently.

const myList = ['apple', 'banana', 'pear']; //const is a way to declare a variable in JavaScript
myList.splice(1, 0, 'mango') //adds mango at index 1, and shifts the remaining elements to the right
//I can print the array using console.log() in JavaScript


[ ‘apple’, ‘mango’, ‘banana’, ‘pear’ ]

If I wanted to delete a couple of the original elements, and add new ones, I could do this:

const myList = ['apple', 'banana', 'pear'];
myList.splice(1, 2, 'mango', 'plum') //starts at index 1, deletes 2 elements, adds mango & plum


[ ‘apple’, ‘mango’, ‘plum’ ]

We could also remove only one element, and add several if we wish:

const myList = ['apple', 'banana', 'pear'];
myList.splice(1, 1, 'mango', 'plum', 'orange', 'grape', 'cherry') //starts at index 1, deletes 1 element, adds mango, plum, orange, grape & cherry


[ ‘apple’, ‘mango’, ‘plum’, ‘orange’, ‘grape’, ‘cherry’, ‘pear’ ]

Notice 'pear' was shifted to the end of the array. We started at index 1, deleted 1 element, and inserted 5 new elements.

Happy coding!

That helps! Thank you so much!

1 Like