The JavaScript Array.pop() method allows you to remove the last item of an Array and will subsequently return that removed item. Array.pop() is a fundamental tool when it comes to manipulating arrays.

Syntax

arr.pop()

Let's Try It Out 💥

Shopping Cart Example 🛒

In this example, let's create an array named shoppingCart that contains 5 items that we picked up at the store.

var shoppingCart = ['book', 'headphones', 'smoothie', 'sandwich', 'candybar']

Great, we have some items in our shopping cart, but at the last minute, we decide that we're trying to be a little bit healthier, and we want to remove the candybar from our shoppingCart. Lucky for us, we can quickly and easily call the Array.pop() method on our shoppingCart array like so:

var shoppingCart = ['book', 'headphones', 'smoothie', 'sandwich', 'candybar']

shoppingCart.pop(); // returns 'candybar'

console.log(shoppingCart); // returns ['book', 'headphones', 'smoothie', 'sandwich']

Try this the code snippet in your browser console.

A Slightly More Real World Shopping Cart Example 🌎 🛒

Here we have our shoppingCart array which contains the same 5 items from before, but now the items are created as Objects, with the properties itemName and price. Objects are a great way to form models of, well...real-world Objects. We could certainly add lots of other properties to these objects, such as a SKU or numberInStock, or whatever else you could imagine, but to keep this example straight forward we will stick with itemName and price.

var shoppingCart = [{ itemName: 'book', price: 9.99}, { itemName: 'headphones', price: 49.99 }, { itemName: 'smoothie', price: 3.99 }, { itemName: 'sandwich', price: 5.99 }, { itemName: 'candybar', price: 1.25 }]

The same way that we used the .pop() method on the original way, we can use it on our seemingly more complex array of objects like so:

var shoppingCart = [{ itemName: 'book', price: 9.99}, { itemName: 'headphones', price: 49.99 }, { itemName: 'smoothie', price: 3.99 }, { itemName: 'sandwich', price: 5.99 }, { itemName: 'candybar', price: 1.25 }]

shoppingCart.pop() // returns { itemName: 'candybar', price: 1.25 }

console.log(shoppingCart); // returns [{ itemName: 'book', price: 9.99}, { itemName: 'headphones', price: 49.99 }, { itemName: 'smoothie', price: 3.99 }, { itemName: 'sandwich', price: 5.99 }];

Combining With Other Array Methods

Keep in mind that you can use other array methods in conjunction with each other. You can use the Array.push() method for adding items to arrays, or the Array.join() method for joining the items in array into a String, and many more methods.

Conclusion

As you can see, the .pop() method has a ton of utility, and it's certainly one of the core fundamentals for manipulating Arrays.

Stay Tuned 📺

If you have any questions or if you'd like to see additional examples, feel free to reach out to me anytime at tim@timwheeler.com, and if you're enjoying my posts, please subscribe below! 👇