Stack Data Structure in Javascript

datastructures

Data Structures

Posted on March 1, 2020

Stack Data Structure in Javascript

Stacks are one of the most common data structures in computer science that one can consider. A stack is an ordered collection of homogeneous data elements,where the insertion and deletion takes place at one end, known as top,which means the element which is inserted last must be deleted first.

The stack is also called as LAST IN FIST OUT(LIFO).

Javascript does not have Stack data structure built into it, but that should not limit you from building one, using the already built-in data types like arrays.

Real-Life Applications of Stack:-

  • Books, Clothes piled on top of each other
  • Floors in a building.

Use cases of stacks in programming -

  • Browser back-forth button.
  • Reversing a string
  • Converting expressions(prefix-infix-postfix)
  • Recursive functions.
  • Maintaining any sort of LIFO data.

Basic Operations

The basic operation that can performed are Insertion, deletion and display.

PUSH(terminology for Insertion) - Inserting or adding the elments into the stack.It places the object on top of the stack.

POP(terminology for Deletion) - Deleting or removing an element from the stack.It removes an object from the top of the stack.

IsEmpty - Reports whether the stack is empty or not.

IsFull - Reports whether the stack exceeds limit or not.

Peek - returns the top record without popping it.

Direction for creating a Stack data Structure in Javascript

Create a stack data structure.The stack should be a class with methods push,pop,and peek.Adding an element to the stack should store it until it is removed.

Examples Usage


const s = new Stack();
s.push(1);
s.push(2);
s.push(3);
s.pop(); //returns 3
s.pop(); // returns 2

//Implementing Stack using arrays
class Stack {
  constructor() {
    // data is a normal array data type built into javascript
    this.data = [];
  }
  //It places the item on top of the stack
  push(item) {
    this.data.push(item);
  }
  // It removes an item from the top of the stack
  pop() {
    return this.data.pop();
  }

  // peek is to return the last record inside of our array without actually removing it.
  peek() {
    return this.data[this.data.length - 1];
  }
}

module.exports = Stack;

In the next article of this series, we will be implementing Stack using Queues in Javascript.

If you are a visual learner,be sure to check this tool out. Its called Quokkajs.It is a developer productivity tool for rapid JavaScript / TypeScript prototyping. Runtime values are updated and displayed in your IDE next to your code, as you type.QuokkaJS

Rapid Prototyping Tool

If you found this article helpful, please tap the drawing Follow this channel for more articles on Data Structures using Javascript.

💖 💪 🙅 🚩
datastructures
Data Structures

Posted on March 1, 2020

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

Sign up to receive the latest update from our blog.

Related