Adding and Removing Values at Array Ends
Introduction
Welcome back to Storing and Updating Lists with JavaScript Arrays. We’ve learned to read values by position and replace them in an array. Now we’ll learn to add and remove values at either end of a list. We’ll use push(), pop(), unshift(), and shift(), paying close attention to what each method returns and how it changes the array.
Changing the Size of a List
As we saw earlier, a const array can still be changed: const prevents us from assigning a different array to the variable, but it does not prevent changes to the array’s contents. Adding or removing a value changes both the contents and the array’s length, while the variable can continue referring to the same array. We’ll make those changes at the ends of a short list.
Adding to the End with push()
Think of push() as adding one more stop at the end of a route. In the example, "Museum" goes after "Depot" and "Park". The method changes the existing array and then returns its new length. We store that returned number in countAfterPush so we can inspect it separately from the array. The next four sections continue this same program in order.
This program adds "Museum" to the end of the array with push() and prints both the array and the value push() returns. The output shows the updated array and the new length.
The first print shows the updated array, and the second shows the value returned by push(). That value is the new count of items, not "Museum". Here, the array has three stops, so countAfterPush is 3.
Removing from the End with pop()
Now we can take the last stop back off the route. pop() changes the array by removing its final value and then returns the value it removed. We save that return value in removedLast, which differs from push() returning a count. The remaining stops stay in their original order.
This program removes the last value with pop() and prints both the removed value and the shortened array. The output shows that "Museum" was removed.
Here, removedLast holds "Museum", while stops is back to ["Depot", "Park"]. The first print displays the removed value; the second displays the shortened array. We can see the contrast: push() adds at the end and returns a length, while pop() removes from the end and returns the removed value.
