Open In App

Implementation of Stack in JavaScript

Last Updated : 11 Jun, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Implementation of a stack in JavaScript involves creating a data structure that follows the Last-In-First-Out (LIFO) principle, where elements are added and removed from the same end. We use stacks to manage function calls, undo functionality, and parse algorithms efficiently in JavaScript applications.

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

Examples: Below is an example of a stack class using an array in JavaScript.

Javascript
// Stack class
class Stack {

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

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

As you can see in 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. 

Methods in Stack

  • Push: Used to add an element to the stack. This method adds an element at the top of the stack.
Javascript
// push function
push(element)
{
    // push element into the items
    this.items.push(element);
}
  • Pop() : Removes an element from the stack, if the function is call on an empty stack it indicates “Underflow”. This method returns the topmost element of stack and removes it. Return underflow when called on an empty stack.
Javascript
// pop function
pop()
{
    // 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();
}
  • Peek() : returns the top most elements in the stack, but doesn’t delete it. It Return the topmost element without removing it from the stack.
Javascript
// peek function
peek()
{
    // return the top most element from the stack
    // but does'nt delete it.
    return this.items[this.items.length - 1];
}

Helper methods

  • isEmpty() : return true if the stack is empty. Returns true if the stack is empty.
Javascript
// isEmpty function
isEmpty()
{
    // return true if stack is empty
    return this.items.length == 0;
}
  • printStack() : This method returns a string in which all the element of an stack is concatenated. 
Javascript
// printStack function
printStack()
{
    let str = "";
    for (let i = 0; i < this.items.length; i++)
        str += this.items[i] + " ";
    return str;
}

Note : Different helper function can be declared in Stack class as per the requirement. Now as we are done with defining the stack class lets use it.

Sample Functions

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

Javascript
// creating object for stack class
let stack = new Stack();

// testing isEmpty and pop on an empty stack

// returns false
console.log(stack.isEmpty()); 

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

Example: Some more functions of stack class 

Javascript
// Adding element to the stack
stack.push(10);
stack.push(20);
stack.push(30);

// Printing the stack element
// prints [10, 20, 30]
console.log(stack.printStack());

// returns 30
console.log(stack.peek());

// returns 30 and remove it from stack
console.log(stack.pop());

// returns [10, 20]
console.log(stack.printStack()); 

Application: Evaluation of Postfix Expression

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

Javascript
class Stack {
    constructor() {
        this.items = [];
    }

    push(element) {
        this.items.push(element);
    }

    pop() {
        if (this.items.length === 0) {
            return "Underflow";
        }
        return this.items.pop();
    }
}

function postFixEvaluation(exp) {
    let stack = new Stack();
    for (let i = 0; i < exp.length; i++) {
        let c = exp[i];
        if (!isNaN(c))
            stack.push(c - '0');
        else {
            let val1 = stack.pop();
            let val2 = stack.pop();
            if (val1 == "Underflow" || val2 == "Underflow")
                return "Can not perform postfix evaluation";
            switch (c) {
                case '+':
                    stack.push(val2 + val1);
                    break;
                case '-':
                    stack.push(val2 - val1);
                    break;
                case '/':
                    stack.push(val2 / val1);
                    break;
                case '*':
                    stack.push(val2 * val1);
                    break;
            }
        }
    }

    return stack.pop();
}

// calling the above method
// returns 9
console.log(postFixEvaluation("235*+8-")); 

// returns "Can not perform postfix evaluation"
console.log(postFixEvaluation("23*+"));

Output
9
Can not perform postfix evaluation



Previous Article
Next Article

Similar Reads

JavaScript Program for Implementation of Stack using Linked List
A stack is a linear data structure that follows the Last In, First Out (LIFO) principle, where elements are added and removed from the same end, known as the top of the stack. Here we'll understand how to implement a stack data structure using a linked list and provide operations such as push, pop, peek, and isEmpty in JavaScript. Using linked list
2 min read
Implementation of Chinese Remainder theorem (Inverse Modulo based implementation)
We are given two arrays num[0..k-1] and rem[0..k-1]. In num[0..k-1], every pair is coprime (gcd for every pair is 1). We need to find minimum positive number x such that: x % num[0] = rem[0], x % num[1] = rem[1], ....................... x % num[k-1] = rem[k-1] Example: Input: num[] = {3, 4, 5}, rem[] = {2, 3, 1} Output: 11 Explanation: 11 is the sm
11 min read
Implementation of stack using Doubly Linked List
Stack and doubly linked lists are two important data structures with their own benefits. Stack is a data structure that follows the LIFO technique and can be implemented using arrays or linked list data structures. Doubly linked list has the advantage that it can also traverse the previous node with the help of "previous" pointer. Doubly Linked Lis
15+ min read
Pattern Occurrences : Stack Implementation Java
Suppose we have two Strings :- Pattern and Text pattern: consisting of unique characters text: consisting of any lengthWe need to find the number of patterns that can be obtained from text removing each and every occurrence of Pattern in the Text. Example: Input : Pattern : ABC Text : ABABCABCC Output : 3 Occurrences found at: 4 7 8 Explanation Occ
12 min read
Infix to Postfix using different Precedence Values for In-Stack and Out-Stack
Conversion of infix to postfix expression can be done elegantly using two precedence function. Each operator is assigned a value (larger value means higher precedence) which depends upon whether the operator is inside or outside the stack. Also the right and left associativity for different operators can be handled by varying it's values in the two
12 min read
Find maximum in stack in O(1) without using additional stack
The task is to design a stack which can get the maximum value in the stack in O(1) time without using an additional stack. Examples: Input: push(2) findMax() push(6) findMax() pop() findMax() Output: 2 inserted in stack Maximum value in the stack: 2 6 inserted in stack Maximum value in the stack: 6 Element popped Maximum value in the stack: 2 Appro
11 min read
Difference between MEAN Stack and Full Stack Developer
MEAN Stack Developer : An IT professional who works on a collection of JavaScript technologies to develop web applications is called a MEAN stack developer. MEAN refers to M for MongoDB (NoSQL database)E for Express (a backend web application framework for Node.js)A for Angular (JavaScript based open-source frontend web framework to develop single
3 min read
Difference between MEAN Stack and LAMP Stack Developer
1. MEAN Stack Developer: MEAN refers to M for MongoDB (No SQL database)E for Express.js (a framework on top of Node.js)A for Angular (a front end framework)N for Node.js (JavaScript runtime environment) MEAN Stack Developer is an IT professional who develops a web application using a collection of JavaScript technologies. Here the database, server
3 min read
Difference between MEAN Stack and MEEN Stack
What are stacks? What is a stack, if you are familiar with full-stack development you might have come across the terms MEAN, MERN, MEVN, MEEN, etc. These are web stacks consisting of a collection of software and frameworks used for building a web application from the front-end and back-end. You can learn any of these stacks to become a Full-stack d
4 min read
Difference between LAMP stack and LEMP stack?
Difference between LAMP and LEMP stack :A Web Stack or Web application stack refers to a compilation of software that is together used to build websites or web applications. To construct a stack basic requirements are : Operating SystemWebserverDatabaseScript Interpreter 1. LAMP Stack :LAMP stack is a collection of Linux OS, Apache Server, MySQL Da
4 min read
Practice Tags :
three90RightbarBannerImg