Ad space (banner)
🟨JavaScript Lessons
Lesson 31 / 69

Stacks and Queues (Basic Data Structures)

In this lesson you'll learn the difference between two fundamental data structures, stacks and queues, so you can choose the right one for the job. This is for people searching "JavaScript stack vs queue" or "JavaScript push pop shift."

A stack is a "last in, first out" data structure — the last thing added is the first thing removed. A queue is "first in, first out" — the first thing added is the first thing removed. Picture the difference between "a stack of books" and "a line of people." In JavaScript, you can easily reproduce either one using array methods.

The sample code reproduces a stack by adding to the end with .push() and removing from the end with .pop(), and reproduces a queue by adding to the end with .push() and removing from the front with .shift(). Notice how the same array methods behave as completely different data structures just by changing where you remove from.

A common beginner stumbling block is the difference between .pop() and .shift(). Both remove one element from an array, but pop removes from the end while shift removes from the front — without understanding that difference, you won't be able to pull data out in the order you intend. It's also worth knowing that shift has to re-index the whole array, so it's more computationally expensive than pop.

In real development, a browser's "back" feature works like a stack, while things like a print queue or waiting your turn for a task work like a queue — these are fundamental data structures that quietly power familiar mechanisms behind the scenes. As a first step into learning data structures and algorithms, it's a basic idea covered by many textbooks.

A great advantage of JavaScript arrays is that they come equipped with general-purpose methods that work for both stacks and queues, letting you reproduce either data structure easily without a dedicated library.

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

Ad space (banner)
Ad space (in-article)