Stacks and Javascript

--

stacks

Stacks are data structures that implement a collection of elements that operates in the LIFO context (last-in first-out), where the last element to be added is the first one to be removed. Stacks generally support three basic operations:

  • Push(), to add elements to the end of the collection.
  • Pop(), to remove the last element from the collection.
  • Peek(), to see the last element from the collection without modifying the collection.

Unfortunately, javascript does not provide a predefined way to use stacks in our code as other programming languages do, such as Java or C++, but it provides us with all the tools to implement it ourselves.

Implementing a stack in javascript

Let’s start by creating a class called Stack

After all, a stack is a collection of elements. let’s implement a constructor and define an array attribute.

Let's implement Push() to add elements to the end of our stack.

Followed by Pop() to remove the last element of the stack.

Last but not least Peek() to see the last element of the stack without modifying the collection.

Iterating over the stack

To iterate over our stack we can use a while loop and check if there is anything at the end of the stack, as followed

Conclusion

Stacks are powerful data structures where the order of operation matters, implementing a stack properly offers a boost on security since you offer constrained access due to its nature. This also brings about its limitation of no providing random access, meaning that in order to get to an element you have to remove all that was added to the collection after it.

--

--

Gary Cordero Rosa
Gary Cordero Rosa

Written by Gary Cordero Rosa

Flatiron School Software Engineering Student

No responses yet