Middle
What is the difference between a queue and a stack? What JS methods are used to work with them?
sobes.tech AI
Answer from AI
A queue and a stack are data structures with different principles of operation:
- Stack operates on the LIFO (Last In, First Out) principle, meaning the last added element is the first to be removed.
- Queue operates on the FIFO (First In, First Out) principle, meaning the first added element is the first to be removed.
In JavaScript, array methods are usually used to work with stacks:
push()— add an element to the end (top of the stack)pop()— remove and return the last element (top of the stack)
For queues:
push()— add an element to the end of the queueshift()— remove and return the first element (head of the queue)
Example of a stack:
const stack = [];
stack.push(1);
stack.push(2);
console.log(stack.pop()); // 2
Example of a queue:
const queue = [];
queue.push(1);
queue.push(2);
console.log(queue.shift()); // 1