Popping elements from a Stack in Javascript


Consider a simple stack class in Javascript.

Example

class Stack {
   constructor(maxSize) {
      // Set default max size if not provided
      if (isNaN(maxSize)) {
         maxSize = 10;
      }
      this.maxSize = maxSize; // Init an array that'll contain the stack values.
      this.container = [];
   }

   // A method just to see the contents while we develop this class
   display() {
      console.log(this.container);
   }

   // Checking if the array is empty
   isEmpty() {
      return this.container.length === 0;
   }
   
   // Check if array is full
   isFull() {
      return this.container.length >= maxSize;
   }

   push(element) {
      // Check if stack is full
      if (this.isFull()) {
         console.log("Stack Overflow!");
         return;
      }
      this.container.push(element);
   }
}

Here the isFull function just checks if the length of the container is equal to or more than maxSize and returns accordingly. The isEmpty function checks if a size of the container is 0. The Push function is used to add new elements into the stack.

 In this section, we are going to add POP operation in this class. Popping elements from a Stack mean removing them from the top of the array. We are taking the end of the container array to be the top of the array as we'll perform all operations with respect to it. So we can implement the pop function as follows −

Example

pop() {
   // Check if empty
   if (this.isEmpty()) {
      console.log("Stack Underflow!");
      return;
   }
   this.container.pop();
}

You can check if this function is working fine using −

Example

let s = new Stack(2);
s.display();
s.pop();
s.push(20);
s.push(30);
s.pop();
s.display();

Output

This will give the output −

[]
Stack Underflow!
[ 20 ]

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 15-Jun-2020

180 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements