a year ago2min read

Implementing a Stack Data Structure in JavaScript

Stack Image

A stack is a fundamental data structure in computer science and programming. It follows the Last-In, First-Out (LIFO) principle, meaning that the last element added to the stack is the first one to be removed. Stacks are used in various applications, such as expression evaluation, backtracking algorithms, and managing function calls.

In this guide, we will explore how to implement a simple stack data structure in JavaScript. We will cover the basic operations of pushing (adding) elements onto the stack, popping (removing) elements from the stack, and checking if the stack is empty.

What is a Stack?

A stack is a linear data structure that operates in two main modes:

  • Push: Adding an element to the top of the stack.
  • Pop: Removing the top element from the stack.

In addition to these core operations, a stack typically supports the following:

  • Peek: Viewing the top element without removing it.
  • isEmpty: Checking if the stack is empty.

Implementing a Stack in JavaScript

Let's create a basic stack class in JavaScript using an array:

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

  // Push element onto the stack
  push(item) {
    this.items.push(item);
  }

  // Pop element from the stack
  pop() {
    if (!this.isEmpty()) {
      return this.items.pop();
    }
  }

  // Peek at the top element
  peek() {
    if (!this.isEmpty()) {
      return this.items[this.items.length - 1];
    }
  }

  // Check if the stack is empty
  isEmpty() {
    return this.items.length === 0;
  }
}

Using the Stack

Now that we have implemented our stack, let's see how to use it:

const myStack = new Stack();

myStack.push(10);
myStack.push(20);
myStack.push(30);

console.log(myStack.peek()); // Output: 30

myStack.pop();
console.log(myStack.peek()); // Output: 20

console.log(myStack.isEmpty()); // Output: false

Next Blogs

Implement Linked-list Using JS.

Learn how to implement a linked list data structure in JavaScript, a fundamental concept for building various data structures and algorithms.

useCounter hook using React.js.

Explore the fundamentals of custom hooks and dive into React's hook system. This tutorial will empower you to build reusable 'useCounter' hooks for better state management in your React applications.