Awesome Javascript
Published in

Awesome Javascript

JS:DS — Stack Data Structure in JavaScript

In this write-up, we are going to see how the stack data structure can be implemented in Javascript.

What is a Stack?

The stack is a data structure to store the data in the order of insertion where the item gets inserted at the last into the stack will be the first one to be removed.
In shorter terms Last In First Out(LIFO).

How are we going to implement it?

The following are the methods and variables we are going to have in Stack DS.

initialize — Initialize the storage and stack size

push — push data to the stack

pop — Remove the last pushed item from the stack

getStackSize — Get the current stack size

initialize

class Stack {  
/* Initialization */
constructor() {
this.storage = {};
this.stackLength = 0;
}
}

push

class Stack {
/* Initialization */
constructor() {
this.storage = {};
this.stackLength = 0;
}

/* Add item to the stack */
push(item) {
this.storage[this.stackLength] = item;
this.stackLength++;
}

}

pop

class Stack {
/* Initialization */
constructor() {
this.storage = {};
this.stackLength = 0;
}

/* Remove Item from the stack with below conditions
1. Get the last index
2. check the stack is non-empty
3. remove the item from the storage
*/
pop() {
let endIndex = this.stackLength - 1;
if (endIndex >= 0) {
delete this.storage[endIndex]
this.stackLength--;
} else {
throw "Stack is Empty, cannot pop!"
}
}

}

getStackSize

class Stack {
/* Initialization */
constructor() {
this.storage = {};
this.stackLength = 0;
}

/* To get the stack size */
getStackSize() {
return this.stackLength;
}
}

Complete Code

We can also add additional features like default stack size, get the last item, etc.,

This article is made with ❤️and special thanks to the dev community from where I learned this.

--

--

Javascript tips, snippets, and Data Structure will be posted. Anyone interested in sharing their knowledge in this publication, you are welcome!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store