Skip to content

Home

JavaScript Data Structures - Queue

Definition

A queue is a linear data structure that behaves like a real-world queue. It follows a first in, first out (FIFO) order of operations, similar to its real-world counterpart. This means that new items are added to the end of the queue, whereas items are removed from the start of the queue.

JavaScript Queue visualization

The main operations of a queue data structure are:

Implementation

class Queue {
  constructor() {
    this.items = [];
  }

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

  dequeue() {
    return this.items.shift();
  }

  peek() {
    return this.items[0];
  }

  isEmpty() {
    return this.items.length === 0;
  }
}
const queue = new Queue();

queue.isEmpty();    // true

queue.enqueue('A');
queue.enqueue('B');
queue.enqueue('C');
queue.enqueue('D');
queue.enqueue('E');

queue.isEmpty();    // false

queue.peek();       // 'A'

queue.dequeue();    // 'A'
queue.dequeue();    // 'B'
queue.dequeue();    // 'C'

More like this

Start typing a keyphrase to see matching snippets.