How to implement a queue in JavaScript

A queue is a data structure that follows FIFO (First In First Out). Think of the queue as a list in which the element that is inserted first will also be accessed first.

Think of it as a ticket counter, where the first person in line will get the first ticket.

A queue follows FIFO

We are going to implement the following six operations for our queue:

  • enqueue() – add an element to the queue
  • dequeue() – remove the first element from the queue
  • peek() – display the last element
  • isEmpty() – check if the queue is empty
  • size() – the total number of elements in the queue
  • clear() – clear all the elements of the queue
// program to implement a queue data structure
class Queue {
constructor() {
this.queue = [];
}
enqueue(element) { // add element
return this.queue.push(element);
}
dequeue() {
if(this.queue.length > 0) {
return this.queue.shift(); // remove first element
}
}
peek() {
return this.queue[this.queue.length - 1];
}
size(){
return this.queue.length;
}
isEmpty() {
return this.queue.length == 0;
}
clear(){
this.queue = [];
}
}
let counter = new Queue();
// add
counter.enqueue(1);
counter.enqueue(2);
counter.enqueue(3);
// get last element
console.log(counter.peek()); // 3
// remove
console.log(counter.dequeue()); // 1
console.log(counter.dequeue()); // 2
console.log(counter.isEmpty()); // false
console.log(counter.size()); // 1
counter.clear();
console.log(counter.size()); // 0

Complexity of queue operations

We are always going to access the first queue element and add new elements at the end of the queue. To do this, we will use:

  • for enqueue – O(1)O(1)
  • for dequeue – O(1)O(1)

Free Resources