DEV Community

Joe Eames for Thinkster

Posted on

Stacks, Queues, and JavaScript Arrays

I love learning the built-in data types as much as possible in JavaScript. Arrays, Objects, etc, these are our hammer and nails. But they're far more versatile than any hammer. You can do a lot of things with a hammer. You can do WAY more things with an Array.

Usually we use arrays to hold a list of items. One of the most frequent operations we know how to do with an array is to add an item to the end using the push() method. Most people also know the pop() method. But there's more you may not know about.

Let's back up just a little bit and talk about stacks and queues. Two of the basic data structures you learn about if you take computer science classes are Stacks and Queues. A stack is a list of data that you can only add items to one end of it, (usually one at a time), and you can only remove items from that same end of that list, (usually one at a time).

It looks like this:

image

This is called a "Last In, First Out" structure. Meaning, the last item that goes INTO the list, is the first item that comes out of the list.

There is also another very similar data structure called a Queue. A Queue is a "First in, First Out" data structure. It looks like this:

image

This kind of data structure has its own benefits compared to the stack, and it can be very useful.

Thankfully JavaScript has our back. They have not only enabled this by giving us an operation that adds items to the beginning of an Array so that we can now use Arrays as Queues but they also kindly added an extra operation that removes items from the front of an Array. This is the shift() and unshift() operators. Although, strangely, they named them exactly backward of what you'd think they mean.

image

Unshift is how you add items to the beginning of the array, and shift removes them. So in this example, "Chewy" would become the new 0 index item, and Luke moves to index 1, Han to 2, etc. and then when we subsequently call shift() "Chewy" gets removed from the beginning, and Luke, Han, Leia go back to positions, 0, 1, 2 respectively.

Learning these other methods and being comfortable with them can really come in handy when solving various problems in your code, so be sure not to ignore them.

Let's practice. Here at Thinkster we practice good educational principles, like learning by DOING. So if you REALLY want to learn them, I've created a short practice exercise for you to learn push, pop, shift, and unshift. Just head over here: https://stackblitz.com/edit/typescript-tfdyau and follow the directions.

Happy Coding!

Enjoy this discussion? Sign up for our newsletter here.

Visit Us: thinkster.io | Facebook: @gothinkster | Twitter: @gothinkster

Top comments (0)