Skip to content

Edvins Antonovs

Implement an array-based Stack data structure in JavaScript

Stack is a popular data structure in computer science which is commonly used in various applications, such as evaluating mathematical expressions and managing memory allocation. A stack is a data structure that follows the last-in-first-out (LIFO) principle, meaning that the last item added to the stack will be the first item to be removed. An array-based Stack data structure organises data in a specific order, where items can only be added or removed from the top of the stack.

In JavaScript, implementing an array-based stack is straightforward and can be done using the built-in array methods.

Initially, I encountered this popular code challenge while preparing for front-end interviews on GreatFrontEnd.

To create a stack, we create a Stack class with a constructor method that initialises an empty array, which will store the items in the stack. The class has the following class methods:

  • push: adds an item to the top of the stack. It takes in a value as an argument and then uses the array's push method to add the value to the end of the array.
  • pop: removes the top item from the stack. It uses the array's pop method to remove the last item from the array and then returns the removed value.
  • peek: returns the top item from the stack without removing it. It uses the array's length property to access the last item in the array and then returns it.
  • isEmpty: checks if the stack is empty. It returns a boolean value based on whether the array is empty.
  • length: returns the number of items in the stack.

Here's an example of how to implement an array-based stack in JavaScript:

1class Stack {
2 constructor() {
3 this.items = [];
4 }
5
6 push(item) {
7 return this.items.push(item);
8 }
9
10 pop() {
11 return this.items.pop();
12 }
13
14 isEmpty() {
15 return this.items.length === 0;
16 }
17
18 peek() {
19 return this.items[this.items.length - 1];
20 }
21
22 length() {
23 return this.items.length;
24 }
25}
© 2024 by Edvins Antonovs. All rights reserved.