Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,038 questions

52,003 answers

573 users

How to implement a stack in Node.js

1 Answer

0 votes
class Stack {
    constructor() {
        this.items = [];
    }

    push(element) {
        return this.items.push(element);
    }

    pop() {
        if (this.isEmpty()) {
            return "Stack is empty";
        }
        return this.items.pop();
    }

    peek() {
        if (this.isEmpty()) {
            return "Stack is empty";
        }
        return this.items[this.items.length - 1];
    }

    isEmpty() {
        return this.items.length === 0;
    }

    size() {
        return this.items.length;
    }

    print() {
        for (let i = 0; i < this.items.length; i++) {
            console.log(this.items[i]);
        }
    }

    clear() {
        this.items = [];
    }
}

// Usage
const stack = new Stack();

stack.push(38);
stack.push(41);
stack.push(42);
stack.push(43);
stack.push(44);
stack.push(45);
stack.push(46);

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:

46
[ 38, 41, 42, 43, 44, 45 ]
45
size: 6
false
38
41
42
43
44
[]

*/

 



answered Aug 15, 2025 by avibootz

Related questions

1 answer 148 views
148 views asked Jan 28, 2022 by avibootz
1 answer 61 views
1 answer 99 views
1 answer 104 views
1 answer 91 views
...