What is stack and queue in JavaScript?

A stack and a queue are both data structures that allow you to store and manipulate elements in a specific order.

A stack is a collection of elements that follows the Last-In-First-Out (LIFO) principle. This means that the last element added to the stack will be the first one to be removed. A common analogy for a stack is a stack of plates, where the plate on top is the one that can be removed next. In JavaScript, you can implement a stack using an array and using the push and pop methods to add and remove elements.

Here is an example of how you can implement a stack in JavaScript:

let stack = [];

// Adding elements to the stack
stack.push(1);
stack.push(2);
stack.push(3);

// Removing elements from the stack
console.log(stack.pop());  // Output: 3
console.log(stack.pop());  // Output: 2
console.log(stack.pop());  // Output: 1

A queue, on the other hand, is a collection of elements that follows the First-In-First-Out (FIFO) principle. This means that the first element added to the queue will be the first one to be removed. A common analogy for a queue is a line of people waiting in line, where the person at the front of the line is the next one to be served. In JavaScript, you can implement a queue using an array and using the push and shift methods to add and remove elements.

Here is an example of how you can implement a queue in JavaScript:

let queue = [];

// Adding elements to the queue
queue.push(1);
queue.push(2);
queue.push(3);

// Removing elements from the queue
console.log(queue.shift());  // Output: 1
console.log(queue.shift());  // Output: 2
console.log(queue.shift());  // Output: 3

In conclusion, a stack and a queue are both useful data structures for storing and manipulating elements in a specific order, but they differ in the order in which elements are removed from the collection. A stack follows the LIFO principle, while a queue follows the FIFO principle.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *