How to implement stack in JavaScript

1 Answer

0 votes
class Stack {
    constructor() {
        this.items = [];
    }
 
    // Push an element onto the stack
    push(element) {
        return this.items.push(element);
    }
 
    // Pop an element from the stack
    pop() {
        if (this.isEmpty()) {
            return "Stack is empty";
        }
        return this.items.pop();
    }
 
    // Peek at the top element
    peek() {
        if (this.isEmpty()) {
        return "Stack is empty";
        }
        return this.items[this.items.length - 1];
    }
 
    // Check if the stack is empty
    isEmpty() {
        return this.items.length === 0;
    }
 
    // Get the size of the stack
    size() {
        return this.items.length;
    }
  
    print() {
        for (let i = 0; i < this.items.length; i++) {
            console.log(this.items[i]);
        }
    }
 
    // Clear the stack
    clear() {
        this.items = [];
    }
}
 
const stack = new Stack();
 
stack.push(12);
stack.push(17);
stack.push(18);
stack.push(19);
stack.push(20);
stack.push(21);
 
console.log(stack.pop());
console.log(stack.items);
   
console.log(stack.peek());
   
console.log("size: " + stack.size());
   
console.log(stack.isEmpty());
   
stack.pop();
stack.print();
   
stack.clear();
console.log(stack.items);
 
 
 
/*
run:
 
21
[ 12, 17, 18, 19, 20 ]
20
size: 5
false
12
17
18
19
[]
 
*/

 



answered Jan 28, 2022 by avibootz
edited Aug 15, 2025 by avibootz
...