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

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (1)

Collapse
 
ramu profile image
Ramu β€’

Cristal clear.. Thanks

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs