DEV Community

Gift Egbonyi
Gift Egbonyi

Posted on • Edited on

Understanding Queues in JavaScript

Hey friends ๐Ÿ‘‹

Even though Iโ€™m a little late this week ๐Ÿ˜ข, letโ€™s keep our DSA series alive!๐Ÿš€ Like I indicated last week, today we're learning about Queues, a very common and beginner-friendly data structure.


A queue works just like a line at the bus stop ๐ŸšŒ:

  • Enqueue โ†’ add a person to the back of the line
  • Dequeue โ†’ let the person at the front leave
  • Peek โ†’ check whoโ€™s at the front without removing them

This is called FIFO (First In, First Out).


Building a Simple Queue in JavaScript

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

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

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

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

  isEmpty() {
    return this.items.length === 0;
  }

  size() {
    return this.items.length;
  }
}

// Example usage:
const queue = new Queue();
queue.enqueue("Alice");
queue.enqueue("Bob");
console.log(queue.peek()); // Alice
queue.dequeue();
console.log(queue.peek()); // Bob
Enter fullscreen mode Exit fullscreen mode

๐ŸŽฎ Try It Yourself

๐Ÿ‘‰ Live Queue Playground on CodePen


๐Ÿ™‹๐Ÿฝโ€โ™€๏ธ Over to You!

Try expanding this queue:

  • Add a Clear Queue button.
  • Show the size of the queue.
  • Animate items sliding when theyโ€™re added or removed.

Let me know if you do the challenge! I'd like to see yours! Connect with me on GitHub

Was this tutorial helpful? Got questions? Or any insight to help me write better tutorials? Let me know in the ๐Ÿ’ฌ!


Thatโ€™s it for todayโ€™s midweek mini tutorial!

Iโ€™m keeping things light, fun and useful; one small project at a time.

If you enjoyed this, leave a ๐Ÿ’ฌ or ๐Ÿงก to let me know.

And if youโ€™ve got an idea for something you'd like me to try out next Wednesday, drop it in the comments. ๐Ÿ‘‡

Follow me to see more straight-forward and short tutorials like this :)

If you are curious about what I do, check out my Portfolio

:-)

Web trails
You can also find me here on LinkedIn
or here X (Twitter)

โœ๐Ÿพ Iโ€™m documenting my learning loudly every Wednesday. Follow along if you're learning JavaScript too!
Letโ€™s keep learning together!

See you next Wednesday, hopefully, not Friday๐Ÿ˜‘ ๐Ÿš€

Top comments (5)

Collapse
 
aksh247 profile image
Akshat Ramanathan

Your dequeue api uses the shift method which I believe is O(n). A better implementation would be to keep 2 items stacks called left and right with their top pointers tracking the enqueue and dequeue operations making them O(1). The data structure is basically 2 stacks stitched together at their ends (the middle).
The operations will run smoothly only edge cases need to be taken care off

Collapse
 
tobi_augenstein profile image
Tobias Augenstein

If I wanted to avoid the array shift, I'd use a map with 2 counters. That also tracks how much has gone through your queue, which might be interesting for debugging or statistics.
But for most cases push/shift should be fine.

class Queue {
  #map = new Map();
  #next = 0;
  #last = -1;

  enqueue(element) {
    this.#map.set(++this.#last, element);
  }

  dequeue() {
    const element = this.peek();
    if (element) {
      this.#map.delete(this.#next++);
      return element;
    }
  }

  peek() {
    return this.#map.get(this.#next);
  }

  size() {
    return this.#map.size;
  }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
giftintech profile image
Gift Egbonyi

This is really efficient for large datasets. Using next and last as pointers and the Map() data structure is on point. I was trying to make the tutorial as beginner-friendly as possible, and even I might not be able to code it like this without help. Thank you!

Collapse
 
giftintech profile image
Gift Egbonyi

True, I was trying to make the code seem intuitive to beginners.
My attempt to make the dequeue() 0(1):

class QueueWithStacks {
  constructor() {
    this.inStack = [];
    this.outStack = [];
  }

  enqueue(element) {
    this.inStack.push(element); // O(1)
  }

  dequeue() {
    if (this.outStack.length === 0) {
      // Transfer elements from inStack to outStack
      while (this.inStack.length > 0) {
        this.outStack.push(this.inStack.pop());
      }
    }
    return this.outStack.pop(); // O(1)
  }

  peek() {
    if (this.outStack.length === 0) {
      while (this.inStack.length > 0) {
        this.outStack.push(this.inStack.pop());
      }
    }
    return this.outStack[this.outStack.length - 1];
  }

  isEmpty() {
    return this.inStack.length === 0 && this.outStack.length === 0;
  }

  size() {
    return this.inStack.length + this.outStack.length;
  }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
aksh247 profile image
Akshat Ramanathan

Now this is ๐Ÿ’ฏ๐Ÿ”ฅ๐Ÿ™Œ๐Ÿป