Easy

Queue

Prompt

Implement a Queue class with the following methods:

  • enqueue(item) — adds an item to the back of the queue
  • dequeue() — removes and returns the item at the front (return null if empty)
  • peek() — returns the front item without removing it (return null if empty)
  • isEmpty() — returns true if the queue has no items
  • size() — returns the number of items

Playground

Hint 1

Use an array as the internal storage. push() adds to the end and shift() removes from the beginning. That gives you FIFO behavior.

Hint 2

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) uses Array.push() to add to the end (the "back" of the line).
  • dequeue() uses Array.shift() to remove from the beginning (the "front" of the line). This is the main difference from a stack, which removes from the end with pop().
  • peek() reads this.items[0] — the front of the queue — without removing it.
  • isEmpty() and size() 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.