Array.shift() method, which is similar to the
Array.pop() method, allows you to remove the first item of an
Array and will subsequently return that removed item.
Array.shift() is a core tool when it comes to working with an
Restaurant Seating Example 🍝
Imagine you own a busy restaurant and naturally you need to track seating within your dining area. When customers come in and there's no seating available, they leave their name, and you hand them one of those little buzzer things 🚨 that alerts them when their table is ready.
This typically works as a FIFO, or 'First In, First Out', system. The first person to come in and place their name on the seating chart is also the first person to be seated, as they have waited the longest.
With that said, the
Array.shift() method is a perfect tool for keeping track of this within your restaurant!
Let's Try It Out 🍽
First we will create an array of customers 👫.
var toBeSeated = ['Andrea', 'Lisa', 'Kevin', 'Jack'];
Awesome! Your restaurant is filling up. We're currently waiting to seat 4 clients.
A Table Becomes Available 🚨
Perfect, a table has now freed up and we are ready to seat the next person. Here we can run the
Array.shift() method on our list of customers that are waiting to be seated which will remove them from the
toBeSeated list and subsequently return us their name.
var toBeSeated = ['Andrea', 'Lisa', 'Kevin', 'Jack']; toBeSeated.shift(); // Returns 'Andrea';
In this case, since
Andrea was the first person in the
toBeSeated array, she was alerted 🚨 that her table was ready, and she was seated. With that said, she was removed from the array, and the next person waiting to be seated should be
View Remaining Customers Waiting To Be Seated 🍻
Just as a sanity check, let's confirm that
Andrea is no longer on the
toBeSeated list, and that the next person up is
var toBeSeated = ['Andrea', 'Lisa', 'Kevin', 'Jack']; toBeSeated.shift(); // Returns 'Andrea'; console.log(toBeSeated); // Returns ['Lisa', 'Kevin', 'Jack'];
Perfect! Just as expected,
Lisa is the next person waiting to be seated.
Combining With Other Array Methods 🤝
As you could imagine, as new customers come in and are added the seating wait-list, you could use other
Array methods such as
Array.push() to add someone to the end of the wait-list, or even
Array.splice() to remove someone who decided to leave before getting their table.
Wrapping Up 📝
As you can see, the
Array.shift() method is super useful, and it's certainly one of the core fundamentals for manipulating
Stay Tuned 📺
If you have any questions or improvements, or if you'd like to see additional examples, feel free to reach out to me anytime at
email@example.com. If you're enjoying my posts, please subscribe below! 👇