stack in javascript 1

stack in javascript

class Stack{
   constructor() 
    { 
        this.items = []; 
    } 
   
    push(element) 
   { 
    // push element into the items 
    this.items.push(element); 
    }
  
    pop() 
    { 
    if (this.items.length == 0) 
        return "Underflow"; 
    return this.items.pop(); 
    } 
  
    peek() 
	{ 
    	return this.items[this.items.length - 1]; 
	} 
  
    printStack() 
    { 
    	var str = ""; 
    	for (var i = 0; i < this.items.length; i++) 
        	str += this.items[i] + " "; 
    	return str; 
    } 

}

Here is what the above code is Doing:
1. We have created a class Stack.
2. We have defined a constructor to initialize the items in the stack when an object is created.
3. We have defined a push() function to insert an element into the stack.
4. We have defined a pop() function to remove an element from the stack.
5. We have defined a peek() function to return the top element of the stack.
6. We have defined a printStack() function to display the stack.

Similar Posts