Flat Preloader Icon

Stack In JS Queue In JS

In JavaScript, both stacks and queues are abstract data types (ADTs) commonly used for organizing and managing data.

Stack:

  • A stack is a linear data structure based on the Last In, First Out (LIFO) principle. In a stack, elements are added and removed from the top only. The most recently added item is the first one to be removed. Think of it as a stack of plates where you can only add or remove plates from the top.

Operations:

  • Push: Adds an element to the top of the stack.
  • Pop: Removes and returns the element from the top of the stack.
  • Peek (or Top): Returns the element at the top of the stack without removing it.
  • isEmpty: Checks if the stack is empty.
				
					class Stack {
    constructor() {
        this.items = [];
    }

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

    pop() {
        if (this.items.length === 0) {
            return "Underflow";
        }
        return this.items.pop();
    }

    peek() {
        return this.items
        [this.items.length - 1];
    }

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

// Example usage:
let stack = new Stack();
stack.push(10);
stack.push(20);
console.log(stack.pop());
// Output: 20
console.log(stack.peek()); 
// Output: 10

				
			

Queue

  • A queue is another linear data structure based on the First In, First Out (FIFO) principle. In a queue, elements are added to the back (end) and removed from the front (beginning) only. The element that has been in the queue the longest is the first one to be removed, similar to people waiting in a line (queue) for a service.

Operations:

  • Enqueue: Adds an element to the back of the queue.
  • Dequeue: Removes and returns the element from the front of the queue.
  • Front: Returns the element at the front of the queue without removing it.
  • isEmpty: Checks if the queue is empty.
				
					class Queue {
    constructor() {
        this.items = [];
    }

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

    dequeue() {
 if (this.items.length === 0) {
return "Underflow";
        }
        return this.items.shift();
    }

    front() {
        if (this.items.length === 0) {
            return "Queue is empty";
        }
        return this.items[0];
    }

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

// Example usage:
let queue = new Queue();
queue.enqueue(10);
queue.enqueue(20);
console.log(queue.dequeue());
// Output: 10
console.log(queue.front()); 
// Output: 20