Data Structure Stack with Javascript - Popular Interview Question

In this post you will learn about such data structure as stack and we will implement it in Javascript.

Stack & Queue

And actually this is a question that you can get on interviews really often. It is either "Please write the implementation of stack" or "What is the difference between stack and queue".

This is why first I want to answer on that specific question.

A stack follows a LIFO (Last In First Out) order, whereas a queue follows a FIFO (First in First Out) order for sorting elements.

Queue diagram

This is the diagram of queue data structure

Stack diagram

And this is the diagram of stack data structure.

So essentially these are similar data structures with this single difference.

Stack implementation

Now let's implement Stack in plain Javascript. Actually it is much easier to implement Stack that Queue and it is really difficult to implement it wrong.

class Stack {
  items = []

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

  pop() {
    this.items.pop()
  }
}

We store elements in items array. To add elements in the array we use push. To implement pop method we just use pop function which removes the last added to the array element and returns it.

We must also implement several helper methods.

class Stack {
  ...
  isEmpty() {
    return this.size() === 0
  }

  size() {
    return this.items.length
  }

  peek() {
    return this.items[this.size() - 1]
  }
}

These are typical helper methods that we implement in the data structure. size returns the amount of elements in the array, isEmpty checks if we have elements at all and peek shows us the next element that will be removed.

Now let's create an instance of Stack and check some methods.

const stack = new Stack()
stack.push({id: '1', name: 'foo'})
stack.push({id: '2', name: 'bar'})
stack.push({id: '3', name: 'baz'})
console.log(stack.size())
console.log(stack.isEmpty())
const firstElement = stack.pop()
console.log(firstElement, stack.items)

Result

Here we see the correct size, our stack is not empty and the element that we removed is the last element that we pushed. So we successfully implemented Stack data structure.

Want to conquer your next JavaScript interview? Download my FREE PDF - Pass Your JS Interview with Confidence and start preparing for success today!

📚 Source code of what we've done
Don't miss a thing!
Follow me on Youtube, Twitter or Instagram.
Oleksandr Kocherhin
Oleksandr Kocherhin is a full-stack developer with a passion for learning and sharing knowledge on Monsterlessons Academy and on his YouTube channel. With around 15 years of programming experience and nearly 9 years of teaching, he has a deep understanding of both disciplines. He believes in learning by doing, a philosophy that is reflected in every course he teaches. He loves exploring new web and mobile technologies, and his courses are designed to give students an edge in the fast-moving tech industry.