This sounds way too simple to be a valuable data structure, right? Let’s talk about a simple use-case — your browser’s back button. You would create a stack of URLs… then push every new URL on top of that stack. If you press the back button, it would pop off the current URL. Let’s take a look at how this would work:
In the first image (top right), we just opened up facebook.com, so we add it on top of the stack of sites that we’ve already visited previously. The second image (middle) is what the stack now looks like while we’re visiting facebook.com. The third image (bottom right) is where we pressed the back button to navigate back to twitter.com, so we pop() off the most recent url.
So you might be wondering why the heck you’d use a stack instead of the array, especially when there are so many built in methods on the Array prototype to utilize! The reasons are two fold:
This implementation does not include swap, empty or peek.
A stack is a data structure based on the principle Last In First Out. stack is container to hold nodes and has two operations — push and pop. The push operation is to add nodes into the stack and pop operation is to delete nodes from the stack and returns the top most node.
Are you ready to take on some more advanced data structures? Next up is the queue!
Having worked across sites raking in over 50 billion website visits annually, Michael Mitrakos can help your business to crush the web game with an award winning website.
I also created Wanderlust Extension to discover the most beautiful places across the world with highly curated content. Check it out!