Stacks and Queues using JavaScript

Implementation of stacks and queues in JavaScript is straightforward. We can use the existing Array object and its method to simulate stacks and queue behaviour. Stacks and queues get the contiguous memory allocation. Elements of stack and queue get the memory (allocation) next to each other. Unlike low-level language C, we do not explicitly create or free memory for the data we are going to use. If you are coming from the C background, you might remember the functions malloc, calloc, and free.

To implement a stack or a queue, we can use the array object and its method without any changes. However, we will create separate objects which will use the array object to define custom functions.

Stack

A stack works on the principle “Last In First Out (LIFO)”. Its implementation in real life is simple and, stacks are around us every day. Think of the pile of books kept on your desk or a deck of card with a rule that you can pick a book or a card from the top.

And that’s the difference between a stack (or a queue) and an array. In an array, we can randomly access elements at any of the indices.

Let’s see the implementation of a stack using an array.

We have used the plain array inside the constructor function. Wrapping everything inside a custom object prevents the random access of elements from the array/stack.

Queue

The implementation of a queue is not a lot different from the stack.

A queue works on “First In First Out (FIFO)”. I am sure I don’t need to give an example of a queue. So let’s jump to the implementation part.