Implementing Stack in javascript

sakethkowtha

sakethk

Posted on August 14, 2021

Implementing Stack in javascript

Hello 👋,

This is an article on implementing stack data structure in javascript

We already know stack is data structure. It has methods like push, pop, top, size and isEmpty

image

push

It will insert the element at first.

pop

It will delete and returns the first element.

top

It will return first element

size

It will return size of an stack i.e no of elements in stack

isEmpty

It will return true if stack doesn't have any elements otherwise it will return false

class Stack {
  constructor(){
    this.list = []
  }

  push(ele){
    this.list.unshift(ele)
  }

  pop(){
    return this.list.shift()
  }

  top(){
    return this.list[0]
  }

  size(){
    return this.list.length
  }

  isEmpty () {
    return this.list.length === 0
  }

}
Enter fullscreen mode Exit fullscreen mode

Usage

const mystack = new Stack()

mystack.isEmpty() // true
mystack.push("a") // returns undefined but it will add element to list
mystack.push("b")
mystack.push("c")
mystack.isEmpty() // false
mystack.top() // c
mystack.pop() // c
mystack.top() // b
mystack.size() // 2
Enter fullscreen mode Exit fullscreen mode

Thank you!!
Cheers!!!

💖 💪 🙅 🚩
sakethkowtha
sakethk

Posted on August 14, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Algorithms Behind JavaScript Array Methods
algorithms Algorithms Behind JavaScript Array Methods

November 1, 2024

Implementing Stack in javascript
javascript Implementing Stack in javascript

August 14, 2021

How to Design an Algorithm
javascript How to Design an Algorithm

August 24, 2020

Common Sorting Algorithms in JavaScript
javascript Common Sorting Algorithms in JavaScript

August 7, 2020