Implementing JavaScript Stack Using Array

In this section, we will explore how to implement a Stack utilizing JavaScript arrays.

What is a Stack

A data structure that operates on the Last In First Out (LIFO) principle. The LIFO principle indicates that elements are organized so that the most recently added element is the first to be removed, while the element that was added first is the last to be removed. A common analogy for understanding this arrangement is that of stacking dishes; the dish that is placed on the top of the stack will be the first one to be used, whereas the dish that was placed at the bottom will be the last to be utilized. This method of organizing elements is referred to as LIFO.

The Stack is characterized by two primary operations: push and pop. These functions are exclusively performed at the top of the Stack. The push function facilitates the addition of elements to the Stack, while the pop function is responsible for extracting or removing an element from the Stack. Both the push and pop actions are executed at the top, as a stack operates on a last-in, first-out (LIFO) principle, meaning that elements can only be added or removed from the top.

Operations on Stack

There are the following operations which are performed on a stack:

  • push: The push operation is used for adding elements to the Stack.
  • pop: The pop operation is used for removing elements from the Stack.
  • peek: The peek operation is used for getting the top element present in the Stack.
  • length: The length operation is used for returning the length of the Stack.
  • search: The search operation is used for searching elements whether present in the Stack.
  • print: The print operation is used for printing elements of the Stack.
  • isEmpty: The isEmpty operation is to check if the stack is empty.

At this point, we will delve into the execution of the Stack data structure along with its associated methods (previously outlined).

Implementing Stack and its operations

To establish a stack data structure, it is essential to develop a stack class as illustrated below:

Example

class stck { 
constructor () {
this.ele = [];
this.top = 0;
}
}

In the above code:

  • We have created a class named stck.
  • Under it, a constructor is created in which we have used two attributes i.e., ele and top. The ele is the array element that will add elements in the Stack, and as we know that in a stack, elements are added from the top of the Stack. So, we have created a top variable which points to the index of the element which is at the top.
  • Both attributes are fetched via this The 'this' keyword is used to get the current value.
  • The push operation

A stack approach for appending elements to the uppermost position.

A practical illustration to comprehend the application of the push method is provided below:

Example

stackpush (e) {
this.ele[this.top] = e;
this.top = this.top + 1;
}

In the above code:

  • We have created a function stackpush in which we have passed an argument as e. The argument e will contain the value that will be inserted in the Stack.
  • Under the function, using this we have accessed the value of e to the ele array and to the top.
  • Now, the value of top is increased by 1 because the top variable has to point to the next empty array index in the Stack.
  • The pop operation

The pop function associated with the Stack is utilized for eliminating or deleting items from the topmost position of the Stack.

Below is an illustration of the stackpop function in action:

Example

stackpop () {
this.top = this.top - 1;
return this.data.pop ();
}

In the code presented above:

  • We have defined a function named stackpop where the initial action is to decrement the value of the top variable by 1. This adjustment is necessary so that the top variable accurately references the location of the preceding element.
  • Following this, the value located at the top of the Stack will be removed using this operator.
  • The length operation

The length function of the Stack is utilized to obtain the size of the Stack by referencing the top variable.

Below is an example of using length operation:

Example

stacklength () {
return this.top;
}

In the code presented above, we have defined a function named stacklength. This function is designed to compute and return the length of the Stack by measuring from its top.

The peek operation

A stack operation designed to retrieve the value located at the pinnacle of the Stack.

Here is an illustration to comprehend the real-world application of the peek function:

Example

peek() {
   return this.data[this.top -1 ];
}
  • In the above code, the peek function returns the element present at the top of the Stack.
  • We have used top - 1 as the top variable points to the top position in the Stack where the element is added.
  • The print operation

The print function serves the purpose of displaying the elements contained within the Stack. In this way, it functions similarly to the printf statement found in C programming.

Here is an illustration demonstrating how to execute the print function:

Example

function print() {
  var t = this.top - 1; // as top variable points to the element position
  while(t >= 0) { 
    console.log(this.data[t]);
    t--;
  }
}

In the above code:

  • We have created a function print where we have initialized a variable t with top - 1 value.
  • Next, a while loop is used in order to print all the values of the Stack from the top.
  • The loop will begin from the last to the top, i.e., upto the 0 th
  • The value on each array index will be printed as per the index value.
  • Lastly, the value is decremented as t--.
  • The reverse operation

The reverse function in a Stack is utilized to invert the sequence of the Stack's elements, allowing for the values within the Stack to be displayed in a reversed arrangement.

Here is an illustration that demonstrates how to implement the reverse function:

Example

function reverse() {
   this.rev(this.top - 1 );
}
function _rev(index) {
   if(index != 0) {
      this.rev(index-1);
   }
   console.log(this.data[index]);
}

In the above code:

  • We have created a function reverse using recursion.
  • After this, another function rev is created that has index as its parameter.
  • Under the rev function, we have used the if statement in which if the index value is not equal to, the reverse stack elements will be calculated.
  • Finally, the reversed stack elements will get printed.
  • These are some of the stack methods which we have practically implemented.
  • Combined Code Implementation

Let’s examine a comprehensive implementation of a stack along with various operations. The example provided is illustrated below:

Example

class stck {
    constructor(){
        this.data = [];
        this.top = 0;
    }
    stackpush(element) {
      this.data[this.top] = element;
      this.top = this.top + 1;
    }
   stacklength() {
      return this.top;
   }
   peek() {
      return this.data[this.top-1];
   }
   isEmpty() {
     return this.top == 0;
   }
  stackpop() {
    if( this.isEmpty() == false ) {
       this.top = this.top -1;
       return this.data.pop(); // last element gets deleted
     }
   }
   print() {
      var t = this.top - 1; 
      while(t >= 0) { 
          console.log(this.data[top]);
           t--;
       }
    }
    reverse() {
       this.rev (this.top - 1 );
    }
    rev(index) {
       if(index != 0) {
          this.rev(index-1);
       }
       console.log(this.data[index]);
    }
}

You are able to execute the aforementioned code and gain practical insights from it.

Input Required

This code uses input(). Please provide values below: