DEV Community

Urfan Guliyev
Urfan Guliyev

Posted on

Stack - Data Structures in JavaScript: Part #2

In this blog, I will talk about our next data structure: a stack.

A stack is a linear data structure that works with the logic of last-in first-out (LIFO). What does it mean? Let’s take a real-life example.

Consider plates stacked in a cabinet.

You put a plate in the cabinet, and then you put another on top of it and then a third one on top of the other and so on. When you want to get a plate, which one do you grab first? You wouldn't normally pull a plate from the middle or bottom. So you grab the last plate you placed first, and the first plate you placed, which is at the bottom of the stack, last.

This is how data is placed in a stack and taken out of it. A stack therefore has 3 basic operations:

  • pop - remove the top item from the stack.
  • push - add an item to the top of the stack.
  • peek - return the top of the stack. JavaScript doesn’t have a built-in method for this.

Alt text of image

So when can we use this data structure ?

The main feature of a stack data structure is that it allows us to first retrive the data that was most recently added. For example, for surfing the web, we could use stack to store all of the user’s most recently visited pages. In this case, stack will enable the user to immediately return to the previous page when he or she clicks the back arrow.

Top comments (0)