Implementation of Stack in JavaScript

We would be implementing Stack Data Structure in Javascript. Stack is a very useful data structure and has a wide range of application. Stack is a linear data structure in which addition or removal of element follows a particular order i.e. LIFO(Last in First Out) AND FILO(First in Last Out). 

Note : Assuming the stack can grow dynamically we are not considering the overflow condition. 

Lets see an example of an stack class using array in Java script:


// Stack class
class Stack {
    // Array is used to implement stack
        this.items = [];
    // Functions to be implemented
    // push(item)
    // pop()
    // peek()
    // isEmpty()
    // printStack()

As you can see the above definition we have created a skeleton of a stack class which contains a constructor in which we declare an array to implement stack. Hence, with the creation of an object of a stack class this constructor would be called automatically. 

Now let’s see implementation of each method:

  • Push: Adds an element to the stack
// push function
    // push element into the items

This method adds an element at the top of the stack.

  • Pop() : Removes an element from the stack, if the function is call on an empty stack it indicates “Underflow” 
// pop function
    // return top most element in the stack
    // and removes it from the stack
    // Underflow if stack is empty
    if (this.items.length == 0)
        return "Underflow";
    return this.items.pop();

This method returns the topmost element of stack and removes it. Return underflow when called on an empty stack.

  • Peek() : returns the top most elements in the stack, but doesn’t delete it. 
// peek function
    // return the top most element from the stack
    // but does'nt delete it.
    return this.items[this.items.length - 1];

Return the topmost element without removing it from the stack.

Helper methods

These are the three basic operation perform by an Stack lets declare some helper method which can be useful while working with stack.

  • isEmpty() : return true if the stack is empty
// isEmpty function
    // return true if stack is empty
    return this.items.length == 0;

Returns true if the stack is empty.

  • printStack() : This method returns a string in which all the element of an stack is concatenated. 
// printStack function
    var str = "";
    for (var i = 0; i < this.items.length; i++)
        str += this.items[i] + " ";
    return str;

Sample Functions

In this example we would create an object of stack class and test few functions of it.

// creating object for stack class
var stack = new Stack();
// testing isEmpty and pop on an empty stack
// returns false
// returns Underflow

Some more functions of stack class

Example :

// Adding element to the stack
// Printing the stack element
// prints [10, 20, 30]
// returns 30
// returns 30 and remove it from stack
// returns [10, 20]

Once we are done with implementing and testing the stack class now we can use it in different application.

In this example, we would use the above stack class to evaluate postfix expression

// Performs Postfix Evaluation on a given exp
function postFixEvaluation(exp)
    var stack = new Stack();
    for (var i = 0; i < exp.length; i++) {
        var c = exp[i];
        if (!isNaN(c))
            stack.push(c - '0');
        else {
            var val1 = stack.pop();
            var val2 = stack.pop();
            if (val1 == "Underflow" || val2 == "Underflow")
                return "Can't perform postfix evaluation";
            switch (c) {
            case '+':
                stack.push(val2 + val1);
            case '-':
                stack.push(val2 - val1);
            case '/':
                stack.push(val2 / val1);
            case '*':
                stack.push(val2 * val1);
    return stack.pop();
// calling the above method
// returns 9
// returns postfix evaluation can't be performed