Stack in JavaScript

Stack Data Structure in JavaScript

let myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];


class Stack{

    constructor() {

        this.items=[]
    }

     push(element) {

       this.items.push(element)

    }

    pop() {

        if (this.items.length == 0) {

            return `Stack is empty`;
        }

        return this.items.pop()
    }

    peek() {
       
        if (this.items.length == 0) {

            return `Stack is empty`;
        }

        return this.items[this.items.length-1]
        
    }

    getSize() {

        return this.items.length;
    }

isEmpty() {

    if (this.items.length == 0) {
        return true
    }

    return false
}
}

const stack = new Stack()
stack.push(50)
stack.push(200)
stack.push(500)
console.log(stack.pop());
console.log(stack.peek());
console.log(stack.getSize());
console.log(stack.isEmpty());


 

About Author

Photo

Hi, I am Mahbub Hasan
Software Engineer

I am very much interested to share my programming
and development knowledge with the people.I will try
to update my blog everyday with new technology inshallah.

Thank You

For Visiting My Blog.

Contact Me