Categories
JavaScript Answers

How to Implement a Stack and a Queue in JavaScript?

Spread the love

Stacks and queues are basic data structures that we may use in our JavaScript programs.

Stacks let us add items to it and the last item that’s added is the first item that can be removed.

Queues let us add items to it and the first item that’s added is the first item that can be removed.

In this article, we’ll look at how to implement a stack and a queue with JavaScript.

JavaScript Stack Methods

JavaScript array comes with methods built-in that make them act like a stack.

The push method lets us add items to the end of the array.

And the pop method lets us remove the last item from the array.

For instance, we can create a stack by writing:

const stack = []
const pushed = stack.push(1, 2)
console.log(stack)
const popped = stack.pop()
console.log(stack, pushed, popped)

The push method lets us append the items that we passed in as arguments into the stack array.

And it returns the last item that’s been appended to the array.

Therefore, pushed is 2.

The pop method lets us remove the last item from thr stack array.

And it returns the popped item.

So popped is 2 and that’s what’s removed from the array.

So stack is [1, 2] when logged from the first console log.

And the 2nd console log will log [1] as the value of stack .

JavaScript Queue Methods

JavaScript arrays also comes with methods that lets us use them as queues.

We use the push method to append items to the queue as we do with stacks.

And we can use the shift method to remove the first item in the array.

For instance, we can write:

const queue = []
const pushed = queue.push(1, 2)
console.log(queue)
const shifted = queue.shift()
console.log(queue, pushed, shifted)

Therefore, the first console log logs [1, 2] as the value of queue .

And in the 2nd console log, queue is [2] .

pushed is 2 and shifted is 1.

shift returns the element that’s added to the beginning of the array.

Size

To get the size of either data structure, we can just use the length property.

So we can log stack.length and queue.length respectively to get their sizes.

Conclusion

We can implement a stack or a queue with JavaScript by using native array methods.

And we get their sizes with the length property.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.