Site icon i2tutorials

Implementing JavaScript Stack Using Array

 

The Last In First Out (LIFO) principle describes a data structure in which elements are placed in Last In First Out order. In general, the LIFO principle refers to the arrangement of elements in such a way that the most recent element is removed first, and the oldest element is removed last. The arrangement of the elements in Stack can be understood as the arrangement of dishing plates in which the plate which was kept first will be used at the end. LIFO refers to such an arrangement.

Stacks are composed of two main functions, push() and pop(). Stack performs both of these operations at the top of the stack. The push() operation inserts/adds elements to the stack, whereas the pop() operation removes/pops elements from the stack. Since elements are always pushed and popped out of a stack from the top, push() and pop() occur at the top.

Operations on Stack

 push() operation

The stack method is used to add elements to the top of the list.

Below is an example of how to use the push() method:

stackpushmethod (e) {  
this.ele[this.top] = e;  
thisthis.top = this.top + 1;  

pop() operation

For removing or deleting elements from the top position of a stack, the pop() method is used.

Below is an example of a stackpop() operation:

stackpopmethod () {  
thisthis.top = this.top - 1;  
return this.data.pop ();  

length () operation

Utilizing the top variable, the length () operation of the Stack returns the stack’s length.

The following example illustrates how to use the length () operation:

stacklengthmethod () {  
return this.top;  

We have created a stacklengthmethod () function that calculates the stack’s length from the top.

peek () operation

This operation retrieves/fetches the value at the top of the stack.

peekmethod() {  
   return this.data[this.top -1 ];  

print () operation

Printing the elements present in the stack is accomplished using the print () operation. As a result, it is similar to the printf function in C programming.

The following example illustrates how print () is implemented:

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

 

Exit mobile version