What is the stack data structure in JS?
What is a stack?
Have you ever wondered how the popular UNDO function that’s present in almost every application really works? Or how the computer keeps track of our visited websites so that when we click back it directs us to our previously visited web page? With stacks, what we are really doing is storing a previous state of our work in the memory so that the last state appears first. This action can’t be done using arrays alone, which is where stacks come in handy.
Example
Imagine a pile of tiles placed in vertical order. If we needed to grab a tile from the middle of the pile, we would need to remove every tile on top of it first. This method is referred to as LIFO (Last In, First Out).
A stack is a last-in-first-out (LIFO) data structure. It has three primitive operations:
- Push: Add an element to the stack
- Pop: Remove an element from the stack
- Peek: Get the topmost element of the stack
Stack in JS
1. Declaring a class
Class stack is declared to initialize an array that will be used to store items of the stack:
class Stack {
constructor()
{
this.items = [];
}
}
2. Push an item
Adds an item in the stack:
push(element)
{
this.items.push(element);
}
3. Pop an item
Removes the last item added in the stack:
pop()
{
if (this.items.length == 0)
return "Underflow";
return this.items.pop();
}
4. Peek
Returns the last item that was pushed in the stack:
peek()
{
this.items[this.items.length - 1];
}
5. isEmpty
Tells whether or not the stack is empty:
isEmpty()
{
return this.items.length == 0;
}
Code
class Stack {// Array is used to implement stackconstructor(){this.items = [];}// push functionpush(element){// push element into the list itemsthis.items.push(element);}// pop functionpop(){if (this.items.length == 0)return "Underflow";return this.items.pop();}// isEmpty functionisEmpty(){// return true if stack is emptyreturn this.items.length == 0;}// peek functionpeek(){return this.items[this.items.length - 1];}}// defining a new stackvar mystack = new Stack()// checking to see if stack is emptyconsole.log(mystack.isEmpty());// Adding elements to the stackmystack.push(1);mystack.push(2);mystack.push(3);// Printing the stack element// prints [1, 2, 3]console.log("printing stack");var str = "";for (var i = 0; i <= mystack.items.length-1; i++){str = str+ mystack.items[i] + " ";}console.log(str);// returns 3console.log("Peek = " + mystack.peek());// removes 3 from stackmystack.pop();// returns [1, 2]console.log("printing stack after pop");str = "";for (var i = 0; i <= mystack.items.length-1; i++){str = str+ mystack.items[i] + " ";}console.log(str);
Free Resources