Queue
Prompt
Implement a Queue class with the following methods:
enqueue(item)— adds an item to the back of the queuedequeue()— removes and returns the item at the front (returnnullif empty)peek()— returns the front item without removing it (returnnullif empty)isEmpty()— returnstrueif the queue has no itemssize()— returns the number of items
Playground
Use an array as the internal storage. push() adds to the
end and shift() removes from the beginning. That gives
you FIFO behavior.
For peek(), the front of the queue is always
this.items[0]. Don't forget to handle the empty case.
Solution
Explanation
A queue is a First-In, First-Out (FIFO) data structure. Think of it like a line at a coffee shop: the first person in line gets served first. New people join at the back, and people leave from the front.
That's the key difference from a stack. A stack is like a stack of plates (last in, first out). A queue is like a line of people (first in, first out).
class Queue {
constructor() {
this.items = [];
}
enqueue(item) {
this.items.push(item);
}
dequeue() {
if (this.isEmpty()) return null;
return this.items.shift();
}
peek() {
if (this.isEmpty()) return null;
return this.items[0];
}
isEmpty() {
return this.items.length === 0;
}
size() {
return this.items.length;
}
}The implementation uses an array where:
enqueue(item)usesArray.push()to add to the end (the "back" of the line).dequeue()usesArray.shift()to remove from the beginning (the "front" of the line). This is the main difference from a stack, which removes from the end withpop().peek()readsthis.items[0]— the front of the queue — without removing it.isEmpty()andsize()work the same as in a stack.
Just like with the stack, we return null from dequeue() and peek() when the queue is empty, instead of letting JavaScript return undefined.
Queues are used for task scheduling (print jobs, CPU task
scheduling), breadth-first search (BFS) in graphs, and
message queues in distributed systems. In JavaScript, the
event loop itself uses a queue: callbacks from
setTimeout and event handlers wait in a queue to be
processed one by one.
Properties vs Methods
A common interview mistake is confusing array properties and methods. length is a property — you access it without parentheses: arr.length. Methods like push(), pop(), and shift() are functions — they need parentheses to execute. Writing arr.length() throws a TypeError, and writing arr.shift without parentheses returns the function itself instead of calling it.