JavaScript: Implement a Stack using Arrays / Objects

1. Introduction

A Stack is a linear data structure that follows the Last In First Out (LIFO) principle. This means the last element added to the stack will be the first element removed. JavaScript does not have a built-in stack, but it can be easily implemented using arrays or objects. In this tutorial, we will implement a Stack using both an Array and an Object.

2. Program Overview

We will:

1. Create a Stack class.

2. Implement essential stack methods: push, pop, peek, and isEmpty.

3. Test our stack implementation.

3. Code Program

// Stack implementation using Array

class StackUsingArray {
    constructor() {
        this.items = []; // Initialize an empty array to store the stack items
    }

    // Add an item to the top of the stack
    push(element) {
        this.items.push(element);
    }

    // Remove and return the top item from the stack
    pop() {
        if (this.isEmpty()) return "Stack is empty"; 
        return this.items.pop();
    }

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

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

// Stack implementation using Object

class StackUsingObject {
    constructor() {
        this.items = {}; // Initialize an empty object to store the stack items
        this.count = 0;  // Maintain a count to track the current position
    }

    push(element) {
        this.items[this.count] = element;
        this.count++;
    }

    pop() {
        if (this.isEmpty()) return "Stack is empty";
        this.count--;
        const result = this.items[this.count];
        delete this.items[this.count];
        return result;
    }

    peek() {
        if (this.isEmpty()) return "Stack is empty";
        return this.items[this.count - 1];
    }

    isEmpty() {
        return this.count === 0;
    }
}

// Test the Stack using Array
const stackArray = new StackUsingArray();
stackArray.push(1);
stackArray.push(2);
console.log(stackArray.peek()); // 2
console.log(stackArray.pop());  // 2
console.log(stackArray.isEmpty()); // false

// Test the Stack using Object
const stackObject = new StackUsingObject();
stackObject.push('A');
stackObject.push('B');
console.log(stackObject.peek()); // 'B'
console.log(stackObject.pop());  // 'B'
console.log(stackObject.isEmpty()); // false

Output:

2
2
false
B
B
false

4. Step By Step Explanation

1. Initialization:

- For the array implementation, we initialize an empty array. For the object implementation, we use an empty object and an additional counter to track the current position.

2. Push Method:

- For arrays, we simply use the push method. For objects, we use the counter as the key to add the element.

3. Pop Method:

- For arrays, we use the native pop method. For objects, we decrement the counter, retrieve the value, delete the key-value pair, and then return the retrieved value.

4. Peek Method:

- This method lets us see the top element without removing it. We fetch the last element for arrays and for objects, we use the count-1 as the key.

5. isEmpty Method:

- Check if the stack is empty by looking at the length for arrays or the counter for objects. 

Both implementations effectively capture the essence of a stack. The choice between array and object largely depends on the specific use case and developer preference.

Comments