Implementing Array stack methods in javascript

A stack is a data structure that holds a list of elements. A stack works based on the LIFO principle i.e., Last In, First out, meaning that the most recently added element is the first one to remove.

Operations on Stack

There are the following operations that 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.

A stack has two main operations that occur only at the top of the stack: push and pop. The push operation places an element at the top of the stack whereas the pop operation removes an element from the top of the stack.

push() method

The push() method allows you to add one or more elements to the end of the array. The push() method returns the value of the length property that specifies the number of elements in the array.

let stack = [];

console.log(stack);  // Output :  [1]

console.log(stack);	 // Output : [1,2]

console.log(stack);  // Output : [1,2,3]

console.log(stack);  // Output : [1,2,3,4]        

Initially, the stack is empty. Each time, we call the push() method to add a number to the stack. After 4 calls, the stack has 4 elements.

pop() method

The pop() method of Stack is used for removing/deleting elements from the top position of the Stack.

let stack = [1, 2, 3, 4, 5 ];

console.log(stack.pop());  // Output : 5
console.log(stack); 	   // Output : [1,2,3,4];

console.log(stack.pop());  // Output : 4
console.log(stack); 	   // Output : [1,2,3];

console.log(stack.pop());  // Output : 3
console.log(stack);		   // Output : [1,2];

console.log(stack.pop());  // Output : 2
console.log(stack); 	   // Output : [1];

console.log(stack.pop());  // Output : 1
console.log(stack);		   // Output : []; -> empty

console.log(stack.pop());  // Output : undefined        

peek() method

It returns the top most elements in the stack, but doesn’t delete them.

length() method

The length() operation is used for returning the length of the Stack.

var array = [1, 2, 3, 4, 5, 10];

// Output : 6        
Posted in

Ankit Patel

Leave a Comment

Your email address will not be published.

Scroll to Top