Understanding Stack Data Structure in JavaScript

Introduction

A Stack is a fundamental data structure in computer science that follows the Last-In-First-Out (LIFO) principle. This means the **last element added** is the **first one to be removed**. 🗂️ In JavaScript, stacks can be implemented using arrays with methods like push() and pop().

📌 What is a Stack?

A stack allows operations primarily at one end, called the **top**. Common operations include:

  • ✔️ push(element) — Add an element to the top of the stack
  • ✔️ pop() — Remove the top element from the stack
  • ✔️ peek() / top() — View the top element without removing it
  • ✔️ isEmpty() — Check if the stack is empty

💡 Implementing Stack Using Arrays

Stack using array

const stack = [];

// Push elements
stack.push(10);
stack.push(20);
stack.push(30);

console.log(stack); // [10, 20, 30]

// Pop element
const removed = stack.pop();
console.log(removed); // 30
console.log(stack);   // [10, 20]

// Peek element
const top = stack[stack.length - 1];
console.log(top);     // 20

🧵 Example: Custom Stack Class

Stack class implementation

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

  // Add element
  push(element) {
    this.items.push(element);
  }

  // Remove element
  pop() {
    if(this.isEmpty()) return "Stack is empty";
    return this.items.pop();
  }

  // View top element
  peek() {
    if(this.isEmpty()) return "Stack is empty";
    return this.items[this.items.length - 1];
  }

  // Check if stack is empty
  isEmpty() {
    return this.items.length === 0;
  }

  // Display stack
  print() {
    console.log(this.items);
  }
}

// Usage
const stack = new Stack();
stack.push(1);
stack.push(2);
stack.push(3);
stack.print(); // [1, 2, 3]
console.log(stack.pop()); // 3
console.log(stack.peek()); // 2

🔗 Applications of Stack

  • 📌 Undo/Redo operations in editors
  • 📌 Function call stack in programming
  • 📌 Expression evaluation and parsing
  • 📌 Backtracking algorithms (e.g., maze solving)

⚠️ Important Notes

Note

  • Stacks follow the **LIFO** principle strictly.
  • JavaScript arrays make stack implementation easy using push() and pop().
  • Custom classes allow more controlled stack operations like peek() and isEmpty().

📊 Quick Reference Table

OperationMethod / ExampleEffect
Pushstack.push(10)Adds 10 to the top
Popstack.pop()Removes and returns top element
Peek / Topstack[stack.length-1]View top element without removing
IsEmptystack.length === 0Check if stack is empty
>>"Stacks are like a stack of plates — you always take the top one first." 🍽️

🔥 Summary

A stack is a simple yet powerful data structure that follows LIFO. In JavaScript, you can use arrays or implement a custom class for better control. Stacks are widely used in programming for undo features, function calls, and parsing expressions.