In this quick post, we'll go over two more widely used JavaScript array methods: pop
and push
.
Array.pop Method
The Array.pop method in JavaScript "pops" the last element from an array and returns it. This mutates (a.k.a. changes) the array that it's used on.
Here's an array of food emojis we will use in the examples below:
const foodEmojis = ["🍕", "🥨", "🌮", "🍔"];
Let's remove the last element, and save it to a new variable:
const removedItem = foodEmojis.pop();
The removedItem
variable now contains 🍔, and the foodEmojis
array contains:
["🍕", "🥨", "🌮"];
Easy, right? 😎
Array.push Method
The Array.push method in JavaScript "pushes" one or more new elements on to the end of an array, and returns the new length. This method also mutates the array, obviously. 😄
Let's add the removedItem
, a.k.a the hamburger (🍔), back to our array:
foodEmojis.push(removedItem);
And then we'll add some cakes (🍰 & 🎂) to our array, because this stuff is a piece of cake:
let arrayLength = foodEmojis.push("🍰", "🎂"); // result: 6
The final contents of foodEmojis
would now be:
[ "🍕", "🥨", "🌮", "🍔", "🍰", "🎂"]
Nice!
YAJG: Yet Another JavaScript 'Gotcha!'
Don't forget, Array.push
does not return the updated array - it returns the length of the updated array! (This is somewhat counterintuitive, and has tripped me up several times...ugh.)
Final Words
Today's post was an extra short one... and there will be lots of these! This is part of my attempt to write VERY frequently, and sometimes I only have a few extra moments in my day. (Like today... 😅)
But don't worry: there will be plenty of longer/more complex posts coming, too! (I have a TON of cooler/more interesting stuff I want to write about... I just need the time. ⌚)