Array push is used to add elements to the end of an Array. In this lesson we'll see how the
push method accepts multiple arguments, can be used to merge two arrays, and how it can be used to represent user input.
Array push is used to add elements to the end of an array. So if we wanted to add a third pet to this pets array, we could simply call pets.push and then provide a value. Log this to the console, you can now see we have a cat, dog, and hamster. Now that calling push on an array is what I would call a destructive update. Meaning that the original array is actually modified in place, and this may be the behavior that you require, but it can also be a source of bugs. That's just something to keep in mind when using push.
Now one of the more interesting facts about array push is that it can take any number of arguments here, so if we pass a second and run that, you can see that both items have now been added to the source array. It's exactly equivalent to doing this. Now that we know that push accepts any number of arguments, we can apply a little trick to enable us to merge two arrays together. Let's pull these out and pretend instead these are in a wish list, and we'll add another one just to illustrate here. We'll add a snake.
Now to merge these two arrays together, we can call apply on the push method, pass in pets as the context, and then the wish list. If we log this to the console you can see now we have all five items. So this is a big improvement over the previous example, because using this technique both the wish list and the source array can now contain any number of items and they'll still both get merged together. This works because calling apply and passing in an array like this is exactly equivalent to doing this.
But obviously the benefit is you don't have to know what these items are ahead of time. Now let's see it in action. Here we have a text input, a button, and a list. To show array push in use we'll use an array to represent the list items. When we type into this input box and click add, we'll push the value onto the array and then display them in the list.
We can say if input.value.length > 0 then we want to add the value onto the pets array. That's where we use push. After adding the item, you probably want to reset the value inside that text field, you can do that by setting it to an empty string. Finally, we want to call render to show the results on screen. If we reload, type dog, click add, you can see dog is added to the list and this is emptied. Now we can add cat and you can see that we are building up this array.