Implementation of Stack in JavaScript

A stack is a Last In First Out (LIFO) data structure where elements are added and removed from the same end, called the top. This article demonstrates how to implement a stack in JavaScript using a class-based approach with basic operations like push, pop, and display.

What is a Stack?

A stack follows the LIFO principle - the last element added is the first one to be removed. Think of it like a stack of plates where you can only add or remove plates from the top.

Item 3 Item 2 Item 1 Push/Pop LIFO Structure

Stack Implementation

Here's a complete stack implementation with push, pop, and display operations:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Stack Implementation</title>
    <style>
        body {
            font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
            padding: 20px;
        }
        .result {
            font-size: 18px;
            font-weight: 500;
            color: blueviolet;
            margin: 10px 0;
        }
        button {
            padding: 8px 12px;
            margin: 4px;
            cursor: pointer;
        }
        input {
            padding: 8px;
            margin: 4px;
        }
    </style>
</head>
<body>
    <h1>Stack Implementation in JavaScript</h1>
    <div class="result"></div>
    
    <input type="text" class="stackPush" placeholder="Enter value">
    <button class="pushBtn">Push</button>
    <button class="popBtn">Pop</button>
    <button class="displayBtn">Display</button>
    
    <h3>Click the buttons above to perform stack operations</h3>
    
    <script>
        let resEle = document.querySelector(".result");
        let pushBtnEle = document.querySelector(".pushBtn");
        let popBtnEle = document.querySelector(".popBtn");
        let displayBtnEle = document.querySelector(".displayBtn");
        let inputEle = document.querySelector(".stackPush");
        
        class Stack {
            constructor() {
                this.items = [];
                this.top = 0;
            }
            
            push(element) {
                this.items[this.top] = element;
                this.top += 1;
            }
            
            pop() {
                if (this.top === 0) {
                    return "Underflow: Stack is empty";
                }
                this.top -= 1;
                let poppedElement = this.items[this.top];
                this.items.length = this.top;
                return poppedElement;
            }
            
            display() {
                if (this.top === 0) {
                    return "Stack is empty";
                }
                return this.items.slice(0, this.top).join(" ? ");
            }
            
            isEmpty() {
                return this.top === 0;
            }
            
            size() {
                return this.top;
            }
        }
        
        let stack1 = new Stack();
        
        pushBtnEle.addEventListener("click", () => {
            let element = inputEle.value.trim();
            if (element === "") {
                resEle.innerHTML = "Please enter a value to push";
                return;
            }
            stack1.push(element);
            resEle.innerHTML = `"${element}" pushed to stack. Size: ${stack1.size()}`;
            inputEle.value = "";
        });
        
        popBtnEle.addEventListener("click", () => {
            let poppedElement = stack1.pop();
            if (poppedElement === "Underflow: Stack is empty") {
                resEle.innerHTML = poppedElement;
            } else {
                resEle.innerHTML = `"${poppedElement}" popped from stack. Size: ${stack1.size()}`;
            }
        });
        
        displayBtnEle.addEventListener("click", () => {
            let stackContent = stack1.display();
            resEle.innerHTML = `Stack contents: [${stackContent}]`;
        });
    </script>
</body>
</html>

Key Stack Operations

Operation Description Time Complexity
push() Add element to top O(1)
pop() Remove top element O(1)
display() Show all elements O(n)
isEmpty() Check if stack is empty O(1)

How It Works

The stack implementation uses an array to store elements and a top pointer to track the current position. When pushing, elements are added at the top index. When popping, the top element is returned and the array size is reduced.

Output Example

When you run the code:

  • Push "Hello": "Hello" pushed to stack. Size: 1
  • Push "World": "World" pushed to stack. Size: 2
  • Display: Stack contents: [Hello ? World]
  • Pop: "World" popped from stack. Size: 1
  • Pop again: "Hello" popped from stack. Size: 0
  • Pop empty stack: Underflow: Stack is empty

Common Use Cases

  • Function calls: JavaScript call stack manages function execution
  • Undo operations: Text editors use stacks for undo functionality
  • Expression evaluation: Converting infix to postfix notation
  • Browser history: Back button functionality

Conclusion

This stack implementation demonstrates the core LIFO principle with essential operations. The class-based approach provides a clean, reusable data structure that can be easily extended with additional methods like peek() or clear() as needed.

Updated on: 2026-03-15T23:18:59+05:30

520 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements