Lesson 7, by Codesarray, , 9 min read

JavaScript stacks and queues: why shift() is slow and the fix

Learn JavaScript stacks and queues: push and pop as a stack, why shift() makes an array an O(n²) queue, a head-pointer Queue class, a Deque, and bracket matching with a stack.

A JavaScript stack and queue are the two simplest data structures in computing, and the ones you will use the most. This page shows why push and pop make an array a perfect stack, why shift() makes it a terrible queue — same 100,000 items, 13.2 seconds against 4.5 milliseconds in our run — and how one extra variable fixes it. Then we build a proper Queue class, a Deque with both ends open, and finish with a stack doing real work: checking that every bracket in a line of code closes in the right order. Everything here ran on Node 24.

A stack: last in, first out

Think of a stack of plates. A clean plate goes on top; when you need one, you take it from the top. Nobody digs a plate out of the middle. Last in, first out — LIFO. Your editor's undo history works exactly like this: every change goes on top of the pile, and Ctrl+Z takes the newest one off.

In JavaScript you don't need a library for this, because an array already is a stack. push adds to the end, pop removes from the end, and both are O(1): plate number one thousand costs the same as plate number three.

const history = [];

history.push("typed 'h'");
history.push("typed 'hi'");
history.push("deleted 'i'");
console.log(history);

const undone = history.pop();
console.log("undo:", undone);
console.log("now:", history);

console.log("peek:", history.at(-1));
[ "typed 'h'", "typed 'hi'", "deleted 'i'" ]
undo: deleted 'i'
now: [ "typed 'h'", "typed 'hi'" ]
peek: typed 'hi'

The end of the array is the top of the stack. pop hands back the newest edit and removes it; at(-1) peeks at the top without removing anything. Push, pop, peek — that's a stack. Nothing else.

A queue: first in, first out

A queue is the same idea, flipped. Think of the line at a coffee shop: you join at the back, the barista serves the front. First in, first out — FIFO. Queues are everywhere in code: print jobs, chat messages, the task queue in the event loop.

The obvious JavaScript move is an array again: push to join at the back, shift() to serve the front. And it works — with ten items you'll never notice anything wrong. But shift is hiding something, and the hint is in the name.

The trap: what shift() really does

An array's items are numbered from zero. When shift removes item 0, every other item has to move down one slot: 1 becomes 0, 2 becomes 1, all the way to the end. It's the coffee line where, when the first person leaves, everyone shuffles forward one step. A hundred people in line means ninety-nine shuffles, every single time someone is served.

That is O(n) work for one shift. Drain the whole line and it's O(n²) — a nested loop you never wrote. Don't take our word for it; measure it with console.time:

const a = Array.from({ length: 100_000 }, (_, i) => i);
let sumA = 0;
console.time("shift queue");
while (a.length > 0) sumA += a.shift();
console.timeEnd("shift queue");

const b = Array.from({ length: 100_000 }, (_, i) => i);
let sumB = 0;
let head = 0;
console.time("pointer queue");
while (head < b.length) sumB += b[head++];
console.timeEnd("pointer queue");
shift queue: 13.239s
pointer queue: 4.453ms

Same 100,000 items, same sums. The second loop never moves anything: one extra variable, head, remembers where the front of the line is, and each pass reads the item at head and moves it forward one slot. Nobody shuffles. That one variable made it about 3,000 times faster — no trick, just no shuffling. (Timings vary by machine; the shape of the gap doesn't.)

A Queue class with a head pointer

That pointer deserves a proper home, so wrap it in a class:

class Queue {
  #items = [];
  #head = 0;

  enqueue(item) {
    this.#items.push(item);
  }

  dequeue() {
    if (this.size === 0) return undefined;
    const item = this.#items[this.#head];
    this.#items[this.#head] = undefined;
    this.#head++;
    return item;
  }

  peek() {
    return this.#items[this.#head];
  }

  get size() {
    return this.#items.length - this.#head;
  }
}

const orders = new Queue();
orders.enqueue("latte");
orders.enqueue("espresso");
orders.enqueue("mocha");
console.log("serving:", orders.dequeue());
console.log("next up:", orders.peek());
console.log("waiting:", orders.size);
serving: latte
next up: espresso
waiting: 2

enqueue is just push: join at the back, O(1). dequeue is where the trick lives. First the guard: on an empty queue it returns undefined instead of crashing. Otherwise it grabs the item at #head, blanks the served slot so JavaScript can free that memory, and moves #head forward. Nothing ever shifts — O(1), every time. size is a getter, length - head, so it counts only the items still waiting even though the used slots are still in the array.

A deque: both ends open

One structure left: the deque — a double-ended queue, and you say it like "deck". Both ends are open: you can add or remove at the front and at the back. Your music app does this every day: "add to queue" puts a song at the back of the line, "play next" pushes it in at the front.

One pointer isn't enough for that, so this class keeps two — #head marks the front, #tail the next free slot at the back — and stores the items in a plain object keyed by those numbers. pushFront moves head down one and stores there; the keys just go negative (-1, -2), and an object doesn't mind at all.

class Deque {
  #items = {};
  #head = 0;
  #tail = 0;

  pushBack(item) {
    this.#items[this.#tail] = item;
    this.#tail++;
  }

  pushFront(item) {
    this.#head--;
    this.#items[this.#head] = item;
  }

  popFront() {
    if (this.size === 0) return undefined;
    const item = this.#items[this.#head];
    delete this.#items[this.#head];
    this.#head++;
    return item;
  }

  popBack() {
    if (this.size === 0) return undefined;
    this.#tail--;
    const item = this.#items[this.#tail];
    delete this.#items[this.#tail];
    return item;
  }

  get size() {
    return this.#tail - this.#head;
  }
}

const playlist = new Deque();
playlist.pushBack("song A");
playlist.pushBack("song B");
playlist.pushFront("play me first");
console.log("now playing:", playlist.popFront());
console.log("then:", playlist.popFront());
console.log("dropped last:", playlist.popBack());
console.log("left:", playlist.size);
now playing: play me first
then: song A
dropped last: song B
left: 0

Every operation is O(1): store at a pointer, move the pointer. popFront and popBack guard the empty case and delete the served slot; size is always tail - head.

Bracket matching with a stack

Now let's make a stack earn its keep. Every editor you've used checks whether your brackets match: each opener needs the right closer, in the right order. The rule is two sentences. See an opener? Push it. See a closer? Pop the stack, and whatever comes off must be its partner.

function isBalanced(code) {
  const stack = [];
  const pairs = { ")": "(", "]": "[", "}": "{" };
  for (const ch of code) {
    if (ch === "(" || ch === "[" || ch === "{") {
      stack.push(ch);
    } else if (ch in pairs) {
      if (stack.pop() !== pairs[ch]) return false;
    }
  }
  return stack.length === 0;
}

console.log(isBalanced("add(nums[0])"));
console.log(isBalanced("add(nums[0)]"));
console.log(isBalanced(")("));
console.log(isBalanced("(()"));
true
false
false
false

pairs maps each closer to the opener it needs. The loop walks the string one character at a time: openers get pushed, and on a closer, the popped bracket is compared with the partner from the table. "add(nums[0)]" fails because the pop gives [ when ( is needed. The last two tests are the edge cases everyone forgets: in ")(", a closer arrives before any opener, so pop() on the empty stack returns undefined, and undefined never matches — the same comparison catches it for free. And in "(()" the loop finishes happily, but a leftover opener means something never closed — that's why the function ends with stack.length === 0 instead of return true. Four verdicts, one pass, one push or pop per character: O(n).

What you learned

  • An array is already a perfect stack: push, pop and at(-1), last in, first out, all O(1).
  • shift() moves every remaining item down one slot, so an array is a slow queue: O(n) per serve, O(n²) to drain — 13.2 s on 100,000 items in our run.
  • A head pointer fixes it: the Queue class serves first in, first out in O(1), guards the empty case with undefined, and blanks served slots so memory frees.
  • A deque opens both ends with two pointers over a plain object: pushBack, pushFront, popFront, popBack, all O(1).
  • A stack of open brackets checks a whole line of code in one pass, with two edge cases: an empty pop (undefined) and a leftover opener.

Common questions

Why is shift() slow but pop() fast? pop removes the last item, so nothing else has to move. shift removes item 0, and every remaining item must be re-indexed one slot down — O(n) work each call. The same asymmetry applies to unshift (slow) versus push (fast).

Should I ever use shift()? For small arrays, yes — shifting ten items is instant and the code is clear. It becomes a problem inside loops over large arrays, where the shifts add up to O(n²). If a queue can grow past a few thousand items, use a head pointer or a queue class.

Why does dequeue() set the slot to undefined instead of deleting it? Blanking the slot (this.#items[this.#head] = undefined) drops the reference so the served item can be garbage-collected, without changing the array's shape. The slot itself stays until the array is dropped; size uses length - head so those used slots are never counted.

What does pop() return on an empty array? undefined — no error is thrown. The bracket checker leans on this: when a closer arrives with nothing on the stack, stack.pop() !== pairs[ch] is comparing undefined with a bracket, which can never match, so the broken string is rejected without a separate empty check.

Is there a built-in queue or deque in JavaScript? No — unlike Python's collections.deque, JavaScript ships neither. An array is fine as a stack, and the two small classes on this page are all a queue or deque needs. Engines do optimise shift for some cases, but the O(n²) drain in the benchmark above is real, so don't rely on it.

Next lesson: linked lists — a list built out of nothing but objects pointing at objects, and when it beats an array (and when it really doesn't).

This article goes with the video JavaScript Stacks and Queues: Why shift() Is Slow and the Fix. Watch it on YouTube.