Skip to content

JavaScript Data Structures: Queue

Queues are similar to stacks, except the insertion point is different from the removal point.

We add at one end of the queue, and we remove from the other end.

This time, we call it First In, First Out (FIFO).

Like any queue you can think of, for example at the restaurant, disco or when you’re waiting to enter into a concert hall.

Here is a possible implementation of a queue in JavaScript using private class fields, using an array as the internal storage:

class Queue {
  #items = []
  enqueue = (item) => this.#items.splice(0, 0, item)
  dequeue = () => this.#items.pop()
  isempty = () => this.#items.length === 0
  empty = () => (this.#items.length = 0)
  size = () => this.#items.length
}

Here’s how to use it: you first initialize an object from the class, then you call its methods:

Example:

const queue = new Queue()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
queue.size() //3

queue.dequeue() //1
queue.dequeue() //2
queue.dequeue() //3

→ Get my JavaScript Beginner's Handbook

I wrote 21 books to help you become a better developer:

  • HTML Handbook
  • Next.js Pages Router Handbook
  • Alpine.js Handbook
  • HTMX Handbook
  • TypeScript Handbook
  • React Handbook
  • SQL Handbook
  • Git Cheat Sheet
  • Laravel Handbook
  • Express Handbook
  • Swift Handbook
  • Go Handbook
  • PHP Handbook
  • Python Handbook
  • Linux Commands Handbook
  • C Handbook
  • JavaScript Handbook
  • Svelte Handbook
  • CSS Handbook
  • Node.js Handbook
  • Vue Handbook
...download them all now!

Related posts that talk about js: