Stack implementation in JavaScript

In this article we will learn the following aspects:

  • Stack definition.
  • Stack common methods.
  • Stack time complexity.
  • Stack implementation using JavaScript.

Stack definition

Stack is a sequential data structure in which we add and remove elements according to LIFO Last in first out or FILO First in last out principles. Each element in the stack is dependent on the others.

Stack common methods

  • push() (storing new element) push an element at the top of the stack.
  • pop() (removing) access and remove element from the stack.
  • peek() (accessing) get the top element in the stack without removing it.
  • isEmpty() check if stack is empty or not.
  • clear() remove all elements from the stack.
  • size() returns stack size (number of elements exist in the stack).

Stack time complexity

  • Accessing has a time complexity of o(n) if you want to access element in the stack you should pop elements till reaching to this element.
  • Searching has a time complexity of o(n).
  • Inserting & Deleting has a time complexity of o(1).

Stacks in real world situation like recursion which pushed the function times and times and execute till reaching the base case it will pop execution from the stack. also web browser when visiting page and another pagers then click on back.

Stack implementation

class Stack{
    /**
     * Define an empty array
     * which represent stack
     * this will be defined during new object initiation
     */
    constructor(){
        this.items=[];
    }
    /**
     * Push operation
     * @param {anyValue} element
     * This function for pushing new elements in the stack 
     */
    push(element){
        this.items.push(element);
    }
    /**
     * Pop operation
     * Remove last element from the stack
     */
    pop(){
        this.items.pop()
    }
    /**
     * Returning the stack size
     * @returns {Number}
     */
    size(){
        return this.items.length;
    }
    peek(){
        return this.items[this.items.length-1];
    }
    /**
     * check if stack is empty or not
     * @returns {Boolean}
     */
    isEmpty(){
        return this.items.length===0;
    }
    /**
     * clear stack remove all elements from the stack
     */
    clear(){
        this.items=[];
    }
}
let stack = new Stack();
stack.push(5);
stack.push(10);
stack.push(20);
stack.push(1400);
console.log(stack.size());
console.log(stack.peek());

Subscribe to our Newsletter

Subscribe to tech-hour website to get all updates, new articles, new courses and projects. No spam ever. Unsubscribe at any time.