DEV Community

Cover image for Stack Data Structure Using Javascript
Nikhil Bobade
Nikhil Bobade

Posted on

Stack Data Structure Using Javascript


A Stack is a commonly used linear data structure a stack data structure follows particular operations that are performed Stack is behaved like Last in first out (LIFO) In this, we have three basic operations.

  1. Push Method
  2. Pop Method
  3. Peek Method
  4. Is Empty Method

Push Method :

The push method is adding data into any type of data into the stack.

Peek Method:

Peek is a very easy operation this method is given you which item or data is on the top of the list so this peek method returns the top element

Pop Method:

Pop is removed the top item from the stack

Is Empty Method:

The is empty method is very important this return if the stack is empty then its return true.

Alt Text

When we use push D is added then call stack on top is D then we use pop then D is removed from the stack.

Stack example using Javascript
//© Inspiration from coding garden

class Stack {
    constructor(){ = {};
        this.size = 0;

    push(item){[this.size] = item;
        this.size +=1

       return[this.size - 1];

        const item = this.peek();
        this.size -= 1;
        return item;

const launguage = new Stack();



Enter fullscreen mode Exit fullscreen mode


Alt Text

I hope you like this also comments about your thoughts.

For more content follow me on Instagram @developer_nikhil27.

If you want to more support me then buy me a coffee.

Thank you.

Top comments (2)

aminnairi profile image

Hi there and thanks for your article, I also like to train my data algorithm in JavaScript. I tend to try and implement them using only functions and recursion if needed. Here is my attempt I wanted to share with you.

const createStack = () => {
  const state = {
    popped: null,
    data: [],

  const stack = {
    push: item => ( = [item,], state.head = item, state.size = state.size + 1, stack),
    pop: () => (state.popped =[0] ?? null, =, state.popped),
    peek: () =>[0] ?? null,
    size: () =>

  return stack;

const language = createStack();


console.log(language);        // [object Object]
console.log(language.pop());  // C++
console.log(language);        // [object Object]
console.log(language.pop());  // JS
console.log(language);        // [object Object]
Enter fullscreen mode Exit fullscreen mode

Not the easiest to read given I used the comma operator pretty much for every method but it gets the job done using some one-liners.

nikhil27b profile image
Nikhil Bobade

Good 👍👍