How to implement stack - JavaScript

Mo Ibra

Mo Ibra

Jan 6, 2023

In this article we will learn how to implementing Stack Data Structure in Javascript.

Stack is a linear data structure in which addition or removal of element follows a particular order i.e. LIFO(Last in First Out).


Create a skeleton of a stack class

Skeleton of a stack class

class Stack {

    // Array is used to implement stack
    constructor() {
        this.items = [];
    }

    // Functions to be implemented:
    // push(item)
    // pop()
    // peek()
    // isEmpty()
    // printStack()
}

Now we have created a skeleton for the class, and when that class is called, we can access the methods and properties of that class, like this:

const stack = new Stack();

But we didn't create any properties or methods for that class, we just did a skeleton, so if we print that class we won't find anything in it.

const stack = new Stack();

console.log(stack);
// Stack { items: [] }

Now let’s see implementation of each method:


Implementation of push method

Now we will implement the push method, and the push method all it do is add an element to the end of the stack.

class Stack {

    // Array is used to implement stack
    constructor() {
        this.items = [];
    }

    // Push method
    push(element) {
        // Add element to end of stack
        this.items.push(element);
    }
}

Now that we've done the implementation, let's do a test for the stack

// Create new stack
const stack = new Stack();

// Print before `push`
console.log(stack);

// Push new element to stack
stack.push('John');

// Print after `push`
console.log(stack);

Output

Stack { items: [] }
Stack { items: [ 'John' ] }

As you can see, the element has been added at the end of the stack.

Now let's create the function that deletes the last element of the stack.

Implementation of pop method

pop method removes the last element from the stack and returns it. Return "underflow" when called on an empty stack.

Implementation

class Stack {

    // Array is used to implement stack
    constructor() {
        this.items = [];
    }

    // Push method
    push(element) {
        this.items.push(element);
    }
    
    // Pop method
    pop() {
        if (this.items.length === 0) return "Underflow";
        return this.items.pop();
    }
}

Now that we've done the implementation, let's do a test for the stack

// Create new stack
const stack = new Stack();

// Print stack
console.log(stack);

// Push method
stack.push('John');
stack.push("Doe");

// Pop last one
console.log(stack.pop());

// Print stack
console.log(stack);

// Pop last one
console.log(stack.pop());

// Print stack
console.log(stack);

// Underflow
console.log(stack.pop());

Output

Stack { items: [] }
Doe
Stack { items: [ 'John' ] }
John
Stack { items: [] }
Underflow

Implementation of peek method

peek method return the topmost element without removing it from the stack.

Implementation

// return the top most element from the stack without delete
peek() {
    return this.items[this.items.length - 1];
}

Now that we've done the implementation, let's do a test for the stack

// Create a stack
const stack = new Stack();

// Push elements
stack.push('John');
stack.push("Doe");

// Print Stack
console.log(stack);

// Peek method
console.log(stack.peek());

Output

Stack { items: [ 'John', 'Doe' ] }
Doe

Now we can say that we are done, but there are some helpers methods that we must implement like isEmpty and printStack.


Implementation of isEmpty method

This function returns true or false, all it does is check whether the stack is empty or not.

Implementation

// check whether the stack is empty or not.
isEmpty() {
    return this.items.length === 0;
}

let's do a test for the stack

// Create a stack
const stack = new Stack();

// Check if isEmpty or not
console.log(stack.isEmpty());

// Push elements
stack.push('John');
stack.push("Doe");

// Print stack
console.log(stack);

// Check if isEmpty or not
console.log(stack.isEmpty())

Output

true
Stack { items: [ 'John', 'Doe' ] }
false

Implementation of printStack method

This method returns a string in which all the element of an stack is concatenated.

Implementation

// Print stack
printStack() {
    var str = "";
    for (let i = 0; i < this.items.length; i++) {
        str += this.items[i] + " ";
    }
    return str;
}

Now that we've done the implementation, let's do a test for the stack

// Stack
const stack = new Stack();

// Push elements
stack.push('John');
stack.push("Doe");

// Print Stack
console.log(stack.printStack());

Output

John Doe 

Full code:

class Stack {

    // Array is used to implement stack
    constructor() {
        this.items = [];
    }

    // Push method
    push(element) {
        this.items.push(element);
    }

    // Pop method
    pop() {
        if (this.items.length === 0) return "Underflow";
        return this.items.pop();
    }
    
    // return the top most element from the stack without delete
    peek() {
        return this.items[this.items.length - 1];
    }

    // check whether the stack is empty or not.
    isEmpty() {
        return this.items.length === 0;
    }

    // Print stack
    printStack() {
        var str = "";
        for (let i = 0; i < this.items.length; i++) {
            str += this.items[i] + " ";
        }
        return str;
    }
}

Thank you for reading

Thank you for reading my blog. 🚀

Suggestions For More Articles: