So here we are going to discuss two paired methods in which we learn how we can add and remove items from the end of an array list.
Push and Pop Method
So the first method we are going to discuss there are push and pop method, we learned to create an array in the last lesson and created an array with variable name fruits and we have 4 fruits stored inside an array.
Here is an example below.
var fruits = ["Strawberry ", " Blueberry ", " Grapes ", " Apple "];
so what if I want to add another element or fruit at the end of this array list, or what if we want to remove the last element of this array list, so to do that we use push() method to add item at the end of array and pop() method to remove item from the end of the array.
So to add an item at the end of array list we use a variable name of the array and then.
Push followed by parentheses and inside parentheses, we write the items that we want to add to an array list.
The syntax for Adding Item into Array List
In our case, we have variable fruit array which consists of 4 items, if we want to add one more item so we use our variable name followed by .push() method. Here is the syntax below:
fruit.push(“items name that we want to add”)
If we want to add Banana at the end of the list so write:
You can see in the below illustration that how we added another item at the very end of the array list.
So if we want to add more than one item at the end of the list, then we write:
We added two more fruits Peach and Blackberry at the end of our array list, so now we have 7 items in our array list.
Here is the output below:
So you can notice in above screenshot, we have added two more fruits to our fruits array and we have got 7 back it is because we have now 7 indexed items in our array list.
When we use our variable name I got back the list of our array.
The syntax is similar to push method but we use pop followed by parentheses instead of push().
Pop() method does not take any arguments like push method.
The syntax for Removing Item from Array List
In our case, we have variable fruit array which consists of 7 items, if we want to remove one more item so we use our variable name followed by .pop() method.
Here is the syntax below:
So when we write above code we get two things, one it returns to me the last item in the array which is Blackberry and another thing is that it removed that Blackberry from our fruits array list.
Here is the output below:
So we use to pop a lot to remove things from the array list.
It’s the easiest way to add and remove items from the array list.
So push takes on or many arguments and it will add to the end of an array and return the length of that array.
While pop takes no arguments and it returns the last item in the array that it removes.
So in this lesson, we have discussed more about array and learn about some of its array methods.
We went over Array push and pop methods and learn how we can add and remove items from the very end of the array list.