How To Implement Stack | In Javascript - letsbug

     Stack an ordered collection of items in which insertion and deletions are allowed only at one end called the top of the stack. Today in this article we are seeing how to implement stacks in Javascript. But before that a little intro to stacks

    Stack is most essential linear data structure. A stack is a non-primitive linear data structure. And most important all the deletion and insertion in a stack is done from top of the stack, the last added element will be the first element to be removed from the stack. That is the reason why stack is also called Last-In-First-Out(LIFO) type of list.

    This is how to define it A stack is an ordered collection of homogeneous data elements where the insertion and deletion operation take place at only one end; called as top of the stack.
  And now

How to implement stack in javascript

    To implement it we will use "class" to create a stack class in javascript. The stack class constructor has two properties that is items which is the list where the elements will be stored and the count to keep the record of element in the list. This method of implementing stack is not the only way of implementing it there are various ways you can implement it.

    And there are various methods in the stack class they are:

  1. push
    • This method is used to add or insert the element in the  stack. As the count is initialize to zero. In this method we add the element and increase the count by one to track its length.
  2. print
    • the print method just loops through the stack element and print then to the screen.
  3. pop
    • pop removes one element from the stack and returns it.
  4. size
    • size method returns the size or length of the stack.
  5. peek
    • As the name says its peeks the stack and returns the first element it sees or finds.
  6. clear
    • To clear the stack clear methods is used.

	
class Stack {
    constructor() {
        this.items = new Array()
        this.count = 0
    }
    push(element) {
        this.items[this.count] = element
        this.count++
    }
    print() {
        let str = ''
        for (let i = 0; i < this.count; i++) {
            str += `${this.items[i]} \n`
        }
        console.log(str)
        return str
    }
    pop() {
        if (this.count == 0) {
            return undefined
        } else {
            let deletedItem = this.items[this.count - 1]
            this.count--
            return deletedItem
        }
    }
    size() {
        return this.count
    }
    peek() {
        return this.items[this.count - 1]
    }
    clear() {
        return this.items = new Array()
    }
}

    Above code is of the stack class now let us test it and initialize it.

	
const stack = new Stack()
    

    This is how to initialize a new class or object in javascript. Now we can call the methods of the stack class and use it.

stack.push(100)
stack.push(200)
stack.push(300)
stack.print()
console.log(stack.size())
stack.pop()
stack.print()
console.log(stack.size())
console.log(stack.peek())
console.log(stack.clear())

we have called every methods that we created here. First we added 100, 200, 300 to the stack and printed it which would just print 100, 200, 300 on the screen.

    Then called size and it returned us the size of the stack which is 3. Then coming to the pop which removed the last element from the stack so now we have only 100, 200 in the stack. So we print that and also check the size of that.

    At the end we peek the stack which returns last element it see in the stack here 200 and at very end we clear the stack that means it has nothing it empty.

100

200

300

3

100

200

2

200

[ ]

Above is the output we would get.

Thankyou

Comments

Categories

Big Data Analytics Binary Search Binary Search Tree Binary To Decimal binary tree Breadth First Search Bubble sort C Programming c++ Chemical Reaction and equation class 10 class 10th Class 9 Climate Complex Numbers computer network counting sort CSS Cyber Offenses Cyber Security Cyberstalking Data Science Data Structures Decimal To Binary Development diamond pattern Digital Marketing dust of snow Economics Economics Lesson 4 Email Validation English fire and ice Food Security in India Footprints Without feet Forest And Wildlife Resources game Geography Geography lesson 6 glassmorphism Glossary Graph HackerRank Solution hindi HTML image previewer India-Size And Location Insertion Sort Internet Network Status Interview Questions Introduction to cyber crime and cyber security IT javascript tricks json to CSV converter lesson 2 lesson 1 lesson 2 Lesson 3 Lesson 6 lesson 7 Life lines of National Economy life processes Linear Search Linked List lowest common ancestor Machine Learning MCQs median in array Merge sort min and max of two numbers Moment Money and Credit My Childhood Natural Vegetation and Wildlife NCERT Network connectivity devices Network Models Network Security No Men Are foreign Node.js operator overloading P5.js PHP Physical features of India Population Prime Numbers python Quick sort R language Rain on the roof Regular Expression Resources and development reversing array saakhi science Searching Algorithm Selection sort Social Media Marketing social science Software Engineering Software Testing Sorting Algorithm Stacks staircase pattern System Concepts Text Recognition The last Leaf time converter Time Passed From A Date Todo List App Tree Trending Technologies Understanding Economic Development username and password video player Visualization water resources Wired And Wireless LAN साखी
Show more

Popular Posts

Big Data MCQs(multiple choice questions) with answers - letsbug

Digital Marketing MCQ(Multiple Choice Questions) with Answers | part 1 | letsbug

Software Engineering MCQs questions with answers - letsbug