DEV Community

Gift Egbonyi
Gift Egbonyi

Posted 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 (0)