DEV Community

Cover image for Using Javascript to Implement Stacks
Collins Mbathi
Collins Mbathi

Posted on • Updated on

Using Javascript to Implement Stacks

Introduction

A stack is a data structure that allows you to store data in a way that allows you to access the data in a last-in, first-out (LIFO) manner. The last data item you add to the stack is the first data item you can remove from the stack.
JavaScript provides several ways to implement stacks. In this article, we'll look at how to use the Array data structure to implement a stack in JavaScript.
In the real world, we can say, for example, when you pile a lot of pancakes together as shown below:

pancakes
As seen in the photo, the last pancake added to the pile will be the first to be removed.

  • It is implemented in undo functionality in applications.
  • In web browsing, the most recent site visited is always the first in the browsing history.

In the following section, we will look at some of the prerequisites for this tutorial.

Prerequisites

The following are required to complete this tutorial:

  • Node.js installed on your system.
  • Sound knowledge of JavaScript.

In the following section, we will now implement stacks.

Now we will implement how a stack works in JavaScript. Here is an example of a stack in JavaScript using an array:

// Stack class
class Stack {

    // Array is used to implement stack
    constructor()
    {
        this.items = [];
    }

    // Methods to be implemented
    // push(value)
    // pop()
    // peek()
    // isEmpty()
    // printStack()
}

Enter fullscreen mode Exit fullscreen mode

As you can see in the preceding example, we created the body of a stack class, which includes a constructor in which we declare an array to implement the stack. As a result, when a stack class object is created, this constructor, as well as some methods for implementing adding and removing values, are automatically called.

Let Us Now Put Each Method Into Action:

1.Push() - This method is used to insert elements into an array.

 push(value) {
     this.items.push(value);

     return this
    }
Enter fullscreen mode Exit fullscreen mode

This method adds a value to the array of items.

2.Pop() - This method is used to remove the array's top element.

pop() {

        if (this.items.length === 0 ) {
            return console.log("empty stack");
        } else {
            return this.items.pop(); 
        }
    }
Enter fullscreen mode Exit fullscreen mode

First, we check to see if the array has elements; if it doesn't, it will return underflow. The pop method will remove the element that was most recently added to the items array.

3.peek - When called, this method returns the array's topmost element. The final component to be added.

 peek () {
        if(this.items.length === 0) {
            console.log("you can't peek an empty array");
        } else {
            return this.items[this.items.length - 1];
        }
    }
Enter fullscreen mode Exit fullscreen mode

As can be seen, it only returns the most recent value added to the stack, the topmost value, but it does not remove it..

  1. isEmpty - In a scenario where we are removing a value from the stack, we use this method to check if the stack is empty and confirm if it is. So that the methods are not executed when the stack contains no values.
isempty() {
        if(this.items.length === 0) {
            console.log("the array is empty");
        }
    }
Enter fullscreen mode Exit fullscreen mode

It returns true when the stack is empty, as shown above.

  1. print() - This is a useful method that returns all of the values in the stack.

// print function
print()
{
    let string = "";
    for (let i = 0; i < this.items.length; i++)
        string += this.items[i] + " ";
    return string;

Enter fullscreen mode Exit fullscreen mode

Now that we've defined the stack class and its methods, let's put them to the test. As an example, consider the following:

const mystack = new Stack();

mystack.push(2);
mystack.push(4);
mystack.push(3);

console.log(mystack.print());
console.log(mystack.peek());
mystack.pop();
console.log(mystack.print());
Enter fullscreen mode Exit fullscreen mode

Now that we've finished implementing and testing our functionality, you can experiment with other application approaches to better understand the stack concept.

Happy coding until my next article.

Top comments (1)

Collapse
 
emma_donery profile image
Emma Donery

Happy Coding πŸŽ‰