DEV Community

sakethk
sakethk

Posted on

2

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!!!

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (1)

Collapse
 
ramu profile image
Ramu •

Cristal clear.. Thanks

đź‘‹ Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay