DEV Community

Cover image for Stack Data Structure in Javascript
Data Structures
Data Structures

Posted on • Edited on

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.

Top comments (6)

Collapse
 
ilya_sher_prog profile image
Ilya Sher • Edited

Poor code quality, do not learn from this

Does not check for underflow. Very thin wrapper around Array, providing close to zero additional functionality.

"Reversing a string" as not a good use case for this class.

Collapse
 
crimsonmed profile image
Médéric Burlet

I really don't understand the purpose of this. You are just creating functions that call already existing functions.

This is a typical WET ( Write Everything Twice ) behavior.

A better example would be to do a stack of object[] where you could have useful extra functions like sorting, reversing the order and more.

Working with arrays would be much faster and economic in terms of memory and speed. And for the peek function you could simply extend the prototype.

if (!Array.prototype.last){
    Array.prototype.last = function(){
        return this[this.length - 1];
    };
};

Adding the following renders your class useless as you can easily have the following:

let myStack = [2, 3, 45, 7, 9, 6]
// let's pop
console.log(myStack.pop()); // output: 6 
// our array is now: [2, 3, 45, 7, 9]
// let's add a new item
myStack.push(18);
// our array is now: [2, 3, 45, 7, 9, 18]
// let's use the prototype extension mentioned earlier
console.log(myStack.last()); // output: 18
// you could then do things like
myStack.reverse()
// this reverses our stack

A faster way that you could also peek would be:

$this.data.reduceRight(a => a);
Collapse
 
math3v profile image
Matej Minárik

Great article! I believe you cheated here a little bit though. The lower level implementation would need to remember the current head (index in the array) and accordingly update the head on push/pop actions. The whole point of implementing a Stack is to learn programming, so it should be done on the lowest level possible. Cheers!

Collapse
 
stearm profile image
Stefano Armenes

typo in your title and also inside the article! "Javacript" 😂

Collapse
 
mohsin708961 profile image
{{7*7}}

Awesome

Collapse
 
jonrandy profile image
Jon Randy 🎖️

This is just wrapping an array object. It doesn't show you know how to implement a stack at all