Computer >> Computer tutorials >  >> Programming >> Javascript

Creating a Stack in Javascript


Though Arrays in JavaScript provide all the functionality of a Stack, let us implement our own Stack class. Our class will have the following functions −

  • push(element): Function to push elements on top of the stack.
  • pop(): Function that removes an element from the top and returns it.
  • peek(): Returns the element on top of the stack.
  • isFull(): Checks if we reached the element limit on the stack.
  •  isEmpty(): checks if the stack is empty.
  • clear(): Remove all elements.
  • display(): display all contents of the array

Let's start by defining a simple class with a constructor that takes the max size of the stack and a helper function display() that'll help us when we implement the other functions for this class. We have also defined 2 more functions, isFull and isEmpty to check if the stack is full or empty.

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.

These will be helpful when we define other operations. The functions we define from this point onwards will all go inside the Stack class.

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);

   }

}