JavaScript: Implement a Stack using Arrays and Objects

Introduction

A stack is a data structure that follows the LIFO (Last In, First Out) principle. This means the last element added to the stack is the first one to be removed. The two main operations in a stack are:

  • Push: Adds an element to the top of the stack.
  • Pop: Removes the top element from the stack.

This guide will walk you through writing a JavaScript program to implement a stack using both arrays and objects.

Problem Statement

Create a JavaScript program that:

  • Implements a stack using both arrays and objects.
  • Allows operations like push (add elements) and pop (remove elements).
  • Displays the elements in the stack after each operation.

Solution Steps

  1. Implement the Stack Using Arrays:
    • Use JavaScript's built-in array methods to add (push) and remove (pop) elements.
  2. Implement the Stack Using Objects:
    • Use an object to store elements and track the top index of the stack.
  3. Display the Stack: Output the stack elements after each operation.

JavaScript Program

Method 1: Implementing a Stack Using Arrays

// JavaScript Program to Implement a Stack using Arrays
// Author: https://www.rameshfadatare.com/

class StackArray {
    constructor() {
        this.stack = [];
    }

    // Push: Add element to the top of the stack
    push(element) {
        this.stack.push(element);
        console.log(`${element} added to the stack`);
    }

    // Pop: Remove element from the top of the stack
    pop() {
        if (this.isEmpty()) {
            console.log("Stack is empty");
            return null;
        }
        const removedElement = this.stack.pop();
        console.log(`${removedElement} removed from the stack`);
        return removedElement;
    }

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

    // Display the stack elements
    displayStack() {
        console.log("Stack:", this.stack);
    }
}

// Example usage
const stackArray = new StackArray();
stackArray.push(1);
stackArray.push(2);
stackArray.push(3);
stackArray.displayStack();
stackArray.pop();
stackArray.displayStack();

Output for Array Stack Example

1 added to the stack
2 added to the stack
3 added to the stack
Stack: [ 1, 2, 3 ]
3 removed from the stack
Stack: [ 1, 2 ]

Method 2: Implementing a Stack Using Objects

// JavaScript Program to Implement a Stack using Objects
// Author: https://www.rameshfadatare.com/

class StackObject {
    constructor() {
        this.stack = {};
        this.top = 0;
    }

    // Push: Add element to the top of the stack
    push(element) {
        this.stack[this.top] = element;
        this.top++;
        console.log(`${element} added to the stack`);
    }

    // Pop: Remove element from the top of the stack
    pop() {
        if (this.isEmpty()) {
            console.log("Stack is empty");
            return null;
        }
        this.top--;
        const removedElement = this.stack[this.top];
        delete this.stack[this.top];
        console.log(`${removedElement} removed from the stack`);
        return removedElement;
    }

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

    // Display the stack elements
    displayStack() {
        console.log("Stack:", this.stack);
    }
}

// Example usage
const stackObject = new StackObject();
stackObject.push(10);
stackObject.push(20);
stackObject.push(30);
stackObject.displayStack();
stackObject.pop();
stackObject.displayStack();

Output for Object Stack Example

10 added to the stack
20 added to the stack
30 added to the stack
Stack: { '0': 10, '1': 20, '2': 30 }
30 removed from the stack
Stack: { '0': 10, '1': 20 }

Explanation

Method 1: Stack Implementation Using Arrays

  • Push: Adds an element to the top of the stack using the push() method.
  • Pop: Removes an element from the top of the stack using the pop() method.
  • isEmpty: Checks whether the stack is empty by comparing the length of the array to 0.
  • displayStack: Prints the current elements of the stack.

Method 2: Stack Implementation Using Objects

  • Push: Adds an element at the top index of the stack and increments the top.
  • Pop: Decrements the top index and removes the element from the object by deleting the property.
  • isEmpty: Checks if the top index is 0, which indicates that the stack is empty.
  • displayStack: Prints the current state of the stack using an object, where each index is a key.

Conclusion

This JavaScript program demonstrates how to implement a stack using both arrays and objects. Both methods support typical stack operations like pushing and popping elements, and either approach can be used depending on the requirements of the application. Arrays are simpler to implement, while objects offer more control over the internal structure and may be more memory-efficient in specific cases.

Comments