Using A Stack in JavaScript
Stack is a Data Structure that works on a basis of Last In, First Out. They give you easy access to the most recent addition to the data structure. Common metaphors to describe Stack are a pile of dishes or a pile of bills. You use the dish on top first, and do not have access to the dish at the bottom [or first added to the stack] until all the other dishes have been removed. Or think of passengers on a full, express train — the last passenger on the train will be the first one to disembark. A Stack is commonly used for functions like the back button on a website or an undo button, since only one layer of information is needed at a time.
The methods to use a Stack are straightforward and often involve the top item in a stack. To add a value to the top of the stack, the syntax is push( ), whereas pop ( ) is the syntax to remove the top value from the stack. If you just want to determine what the top value of a stack is, you can use peek( ).
To determine how many items are in a stack, the method length( ) can be used. isEmpty( ) will return true if the stack is empty and will return false if it contains a value. You can also use two (or more) Stacks at a time to interact with data.
Let’s say we’re needing to track boarding groups for an amusement park ride, like Tower of Terror at Walt Disney World. If boarding groups are made up of eight people, we can use stack_1 to determine Boarding Group One.
We can easily make the boarding group larger or smaller by changing i < 8 to either i < 4 (for ride vehicles seating four) or i < 10 (for ride vehicles seating ten).
Get Elaine Doud’s stories in your inbox
Join Medium for free to get updates from this writer.
We can then implement stack_2 if we want to move guests from the boarding group to the actual ride.
Stacks are an easily accessible data structure to work with to keep track and organize data.
Sources:
“Implementation of Stack in JavaScript” Geeks for Geeks. <https://www.geeksforgeeks.org/implementation-stack-javascript/>
“Implementing JavaScript Stack Using an Array” JavaScript Tutorial. <https://www.javascripttutorial.net/javascript-stack/>
“Deep Dive into Data structures using Javascript — Stack” Sahin Arslan.
<https://www.sahinarslan.tech/posts/deep-dive-into-data-structures-using-javascript-stack>










