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:
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:
This kind of data structure has its own benefits compared to the stack, and it can be very useful.
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.
Enjoy this discussion? Sign up for our newsletter here.