JavaScript: What are Stack and Queue?

Source

Data structure is a very important topic that is often asked during technical interviews and mandatory course in school. Today, I want to dive into the two of the most common data structures: stack and queue.


What is a Stack?

A stack is a type of data structure that is linear where order is conserved. For many people, stack is known to have a LIFO (Last In First Out) mechanism. Let’s take a look at an example of a stack in real life: stack of plates.

Source

If you weren’t allow to take plates from the middle and all you can only see the top most plate, this is a stack!

Now that we know how a stack works, let’s implement it in JavaScript! In our implementation we will write the basic methods for a stack like push, pop, and peek.

Implementation #1 (Array)

Implementation #2 (Linked List)

What is a Queue?

Similar to a stack, queue is a linear data structure where it obeys the FIFO (First In First Out) mechanism. You can think of a queue as a single line of people at a fast food restaurants.

Source

Given that no one cuts anyone, first person on the line will get to order the food first and the last person will be the last one to order. This is an example of a queue!

Now that we know how a queue works, let’s implement it in JavaScript! In our implementation we will write the basic methods for a queue like enqueue, dequeue, and peek.

Implementation #1 (Array)

Implementation #2 (Linked List)


Those are stack and queue implemented in JavaScript!

Thank you so much everyone for the read! You can also check my other JavaScript posts through my profile.

Basics of JavaScript:

Variable: https://medium.com/@timhancodes0281/basics-of-javascript-variable-3eb6f4f0af18
Data Types: https://medium.com/@timhancodes0281/basics-of-javascript-data-types-385bab24b51

JavaScript Fundamentals

Prototypal Inheritance: https://medium.com/javascript-in-plain-english/javascript-fundamental-prototypal-inheritance-9153ab434aae

ES6

Rest/Spread Operator in JavaScript: https://medium.com/javascript-in-plain-english/rest-spread-operator-in-javascript-2da13aa942fb
Array Methods Cheatsheet: https://medium.com/@timhancodes/javascript-array-methods-cheatsheet-633f761ac250

Merge Sort

Merge Sort Algorithm in JavaScript: https://medium.com/javascript-in-plain-english/javascript-merge-sort-3205891ac060