There are many more array methods than just
.push() mutate the array on which they’re called. However, there are times that we don’t want to mutate the original array and we can use non-mutating array methods. Be sure to check MDN to understand the behavior of the method you are using.
.concat() amongst many others. Using these built-in methods make it easier to do some common tasks when working with arrays.
Below, we will explore some methods that we have not learned yet. We will use these methods to edit a grocery list. As you complete the steps, you can consult the Codecademy Docs to learn what each method does!
Under the code added in step 1, use the
.unshift() method to add
'popcorn' to the beginning of your grocery list.
groceryList to the console.
You may wish to delete the
console.log() statement from the previous step.
.unshift() in Docs.
You’re in a hurry so you decide to ask a friend to help you with your grocery shopping. You want him to pick up the
'coffee beans', and
Under the code you added for step 2, use
.slice() to provide your friend with a list of these three things.
Log this part of the list to the console. Unlike the two previous checkpoints, you should do both of these steps in one line.
.slice() in Docs.
groceryList, log the grocery list to the console one more time.
Notice that the
groceryList array still contains the same items it had in Step 2. That means
.slice() is non-mutating! You can confirm this in the link in the previous step.
Let’s find the index of a particular element in
groceryList to find the index of the element
'pasta' and save the returned value to a
const variable named
pastaIndex to the console. (You may remove the other
console.log() statements to declutter the terminal.)
.indexOf() in Docs.