DEV Community

Mrityunjay-Palled
Mrityunjay-Palled

Posted on

Implementing a Stack in JavaScript

Stack is one on the most common and widely used data-structure. stack follows the LIFO(Last In First Out) policy.

Image description

In the above image, we can see the stack of books. If we notice carefully, we can add a new book only from the top. Likewise, we can only remove the book from the top. which is pretty much a similar analogy to how the stack data-structure works.

Stack Implementation:

Image description

Now let's take a look at each individual operation that can be performed on the stack.

PushElement():It is used to insert an element on top of the stack.

Image description

PopElement():It deletes the topmost element of the stack and returns it.

Image description

isEmpty():This method returns true if the stack is empty; otherwise, it returns false.

Image description

Peek():This method returns the topmost element of the stack without actually deleting it.

Image description

Print():This method is used to print all the elements present in the stack.

Image description

Adding elements to the stack and printing them: We can add new elements to the stack using PushElement() and we can print them using Print()

Image description

Removing the topmost element and printing the remaining elements in the stack: For removing the topmost element of the stack we can use the PopElement() method and for printing we can use the Print() method

Image description

If we take a closer look, we removed the top most element from the stack, which is 60.

Checking whether the given stack is empty or not: For checking whether the stack is empty or not we can use isEmpty() method

Image description

In our case the stack is not empty so the isEmpty() method returns false

Getting the topmost element of the stack without deleting it: To get the top most element of the stack without actually deleting it we can use Peek() method.

Image description

Here we can see that Peek() is returning the top most element which is 50 without actually deleting it from the stack

Stack Underflow: This occurs when you try to remove or get the top most element of the stack when the stack is empty.

Stack Overflow: This occurs when you try to add a new element to the stack which is already full

Top comments (0)