What is the stack data structure in JS?

What is a stack?

Have you ever wondered how the popular UNDO function that’s present in almost every application really works? Or how the computer keeps track of our visited websites so that when we click back it directs us to our previously visited web page? With stacks, what we are really doing is storing a previous state of our work in the memory so that the last state appears first. This action can’t be done using arrays alone, which is where stacks come in handy.

Example

Imagine a pile of tiles placed in vertical order. If we needed to grab a tile from the middle of the pile, we would need to remove every tile on top of it first. This method is referred to as LIFO (Last In, First Out).

A stack is a last-in-first-out (LIFO) data structure. It has three primitive operations:

  • Push: Add an element to the stack
  • Pop: Remove an element from the stack
  • Peek: Get the topmost element of the stack
stack
stack

Stack in JS

1 of 6

1. Declaring a class

Class stack is declared to initialize an array that will be used to store items of the stack:

class Stack { 
 
    constructor() 
    { 
        this.items = []; 
    } 
  
} 

2. Push an item

Adds an item in the stack:

push(element) 
{  
    this.items.push(element); 
} 

3. Pop an item

Removes the last item added in the stack:

pop() 
{     
    if (this.items.length == 0) 
        return "Underflow"; 
    return this.items.pop(); 
} 

4. Peek

Returns the last item that was pushed in the stack:

peek() 
{ 
   this.items[this.items.length - 1]; 
} 

5. isEmpty

Tells whether or not the stack is empty:

isEmpty() 
{    
    return this.items.length == 0; 
} 

Code

class Stack {
// Array is used to implement stack
constructor()
{
this.items = [];
}
// push function
push(element)
{
// push element into the list items
this.items.push(element);
}
// pop function
pop()
{
if (this.items.length == 0)
return "Underflow";
return this.items.pop();
}
// isEmpty function
isEmpty()
{
// return true if stack is empty
return this.items.length == 0;
}
// peek function
peek()
{
return this.items[this.items.length - 1];
}
}
// defining a new stack
var mystack = new Stack()
// checking to see if stack is empty
console.log(mystack.isEmpty());
// Adding elements to the stack
mystack.push(1);
mystack.push(2);
mystack.push(3);
// Printing the stack element
// prints [1, 2, 3]
console.log("printing stack");
var str = "";
for (var i = 0; i <= mystack.items.length-1; i++){
str = str+ mystack.items[i] + " ";
}
console.log(str);
// returns 3
console.log("Peek = " + mystack.peek());
// removes 3 from stack
mystack.pop();
// returns [1, 2]
console.log("printing stack after pop");
str = "";
for (var i = 0; i <= mystack.items.length-1; i++){
str = str+ mystack.items[i] + " ";
}
console.log(str);

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved