---
title: "Stack and Queue Data Structures"
url: https://khanwaseem.com/blog/data-structure-and-algorithm/stack-and-queue-data-structures
author: "khan Waseem"
published: 2026-11-22
updated: 2026-11-22
topics: ["Data Structure and Algorithm", "Blog"]
description: "Understand stacks (LIFO) and queues (FIFO), implement both in JavaScript, and solve classic problems like balanced brackets and breadth-first processing."
---

# Stack and Queue Data Structures

Table of Contents

[Toggle](#)

- [Introduction:](#introduction)
- [The Stack](#the-stack)[Stack Operations:](#stack-operations)
- [Implementing a Stack in JavaScript:](#implementing-a-stack-in-javascript)
- [Example: Checking Balanced Brackets:](#example-checking-balanced-brackets)
- [Where Stacks Are Used:](#where-stacks-are-used)

- [The Queue](#the-queue)[Queue Operations:](#queue-operations)
- [Implementing a Queue in JavaScript:](#implementing-a-queue-in-javascript)
- [Example: Processing Tasks in Order:](#example-processing-tasks-in-order)
- [Types of Queues:](#types-of-queues)
- [Where Queues Are Used:](#where-queues-are-used)

- [Stack vs Queue at a Glance](#stack-vs-queue-at-a-glance)
- [Conclusion:](#conclusion)

## Introduction:

Stacks and queues are two of the simplest and most useful data structures in computer science. Both store a collection of items, and both limit **where** you can add and remove items. That limit is exactly what makes them useful: it guarantees the order in which items come out.

- A **stack** is **Last In, First Out (LIFO)**: the last item you add is the first one you remove.

- A **queue** is **First In, First Out (FIFO)**: the first item you add is the first one you remove.

## The Stack

Think of a stack of plates. You put a new plate on top, and you take a plate from the top. You never pull one out from the middle.

```
push(3)      pop() -> 3
  | 3 |        |   |
  | 2 |        | 2 |
  | 1 |        | 1 |
  +---+        +---+
```

### Stack Operations:

- **push(item)** – add an item to the top. O(1)

- **pop()** – remove and return the top item. O(1)

- **peek()** – look at the top item without removing it. O(1)

- **isEmpty()** – check whether the stack is empty. O(1)

### Implementing a Stack in JavaScript:

A JavaScript array already has `push` and `pop` at the end, which are both O(1), so a stack is easy to build on top of it:

```javascript
class Stack {
  constructor() {
    this.items = [];
  }

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

  pop() {
    if (this.isEmpty()) return undefined;
    return this.items.pop();
  }

  peek() {
    return this.items[this.items.length - 1];
  }

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

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

const stack = new Stack();
stack.push(1);
stack.push(2);
stack.push(3);
console.log(stack.pop());  // 3
console.log(stack.peek()); // 2
console.log(stack.size);   // 2Code language: JavaScript (javascript)
```

### Example: Checking Balanced Brackets:

A classic stack problem: is a string like `{[()]}` balanced? Every time we see an opening bracket we push it. Every time we see a closing bracket, the top of the stack must be its matching opening bracket.

```javascript
function isBalanced(text) {
  const pairs = { ")": "(", "]": "[", "}": "{" };
  const stack = [];

  for (const char of text) {
    if (char === "(" || char === "[" || char === "{") {
      stack.push(char);
    } else if (pairs[char]) {
      if (stack.pop() !== pairs[char]) return false;
    }
  }

  return stack.length === 0;
}

console.log(isBalanced("{[()]}"));      // true
console.log(isBalanced("([)]"));        // false
console.log(isBalanced("if (a[0]) {}")); // trueCode language: JavaScript (javascript)
```

### Where Stacks Are Used:

- **The call stack:** every time a function is called, JavaScript pushes it onto the call stack, and pops it when the function returns. Infinite recursion causes a “Maximum call stack size exceeded” error because the stack overflows.

- **Undo** in editors: each action is pushed; undo pops the last one.

- **Back button** in browsers.

- **Parsing** expressions and checking brackets in code editors.

- **Depth-first search** in graphs and trees.

## The Queue

Think of a line at a ticket counter. New people join at the back, and the person at the front is served first.

```css
enqueue ->  [ 4 | 3 | 2 | 1 ]  -> dequeue
            back          frontCode language: CSS (css)
```

### Queue Operations:

- **enqueue(item)** – add an item to the back. O(1)

- **dequeue()** – remove and return the item at the front. O(1)

- **peek()** – look at the front item. O(1)

- **isEmpty()** – check whether the queue is empty. O(1)

### Implementing a Queue in JavaScript:

You might be tempted to use an array with `push` and `shift`. It works, but `shift()` is O(n), because every remaining element moves one position to the left. For large queues that gets slow. A better approach keeps the items in an object and tracks the index of the front and back:

```javascript
class Queue {
  constructor() {
    this.items = {};
    this.head = 0; // index of the front item
    this.tail = 0; // index where the next item goes
  }

  enqueue(item) {
    this.items[this.tail] = item;
    this.tail++;
  }

  dequeue() {
    if (this.isEmpty()) return undefined;
    const item = this.items[this.head];
    delete this.items[this.head];
    this.head++;
    return item;
  }

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

  isEmpty() {
    return this.tail === this.head;
  }

  get size() {
    return this.tail - this.head;
  }
}

const queue = new Queue();
queue.enqueue("Alice");
queue.enqueue("Bob");
queue.enqueue("Charlie");
console.log(queue.dequeue()); // "Alice"
console.log(queue.peek());    // "Bob"
console.log(queue.size);      // 2Code language: JavaScript (javascript)
```

Now both `enqueue` and `dequeue` are O(1). A queue can also be built on a linked list with a `head` and `tail` pointer, which you learned about in the previous lesson.

### Example: Processing Tasks in Order:

```javascript
const printQueue = new Queue();
printQueue.enqueue("report.pdf");
printQueue.enqueue("invoice.pdf");
printQueue.enqueue("photo.png");

while (!printQueue.isEmpty()) {
  console.log("Printing", printQueue.dequeue());
}
// Printing report.pdf
// Printing invoice.pdf
// Printing photo.pngCode language: JavaScript (javascript)
```

### Types of Queues:

- **Simple queue:** the FIFO queue above.

- **Circular queue:** a fixed-size queue where the back wraps around to the start of the storage, so no space is wasted. Used in buffers for audio, video and network data.

- **Priority queue:** each item has a priority, and the highest-priority item leaves first, no matter when it arrived. It is usually built with a heap, which we covered in the Heap Sort lesson.

- **Deque (double-ended queue):** items can be added and removed at both ends.

### Where Queues Are Used:

- **Task and job queues** on servers, such as sending emails in the background (RabbitMQ and Kafka, covered in the System Design course, are queues at a much larger scale).

- **The JavaScript event loop:** callbacks wait in a task queue until the call stack is empty.

- **Printers, call centres and ticket systems** that serve requests in order.

- **Breadth-first search** in graphs and trees, which visits nodes level by level.

## Stack vs Queue at a Glance

- **Order:** stack is LIFO, queue is FIFO.

- **Add:** stack uses `push` (top), queue uses `enqueue` (back).

- **Remove:** stack uses `pop` (top), queue uses `dequeue` (front).

- **Typical algorithm:** stack for depth-first search and backtracking, queue for breadth-first search and scheduling.

## Conclusion:

Stacks and queues are simple to build but appear everywhere: in the JavaScript call stack and event loop, in undo buttons, in job queues and in graph algorithms. You learned how each one works, implemented both with O(1) operations in JavaScript, and solved the balanced brackets problem with a stack. In the next lesson we move from linear structures to hierarchical ones with binary trees and binary search trees.

### Related posts:

[Binary Tree and Binary Search Tree](https://blog.khanwaseem.com/binary-tree-and-binary-search-tree/)
[Linked List Data Structure](https://blog.khanwaseem.com/linked-list-data-structure/)
[CSS – Flex](https://blog.khanwaseem.com/css-flex/)
[What is RabbitMQ?](https://blog.khanwaseem.com/what-is-rabbitmq/)

Powered by [YARPP](https://yarpp.com).
