JavaScript Stacks, Queues and Flattening: push, pop, shift, unshift, concat, flat and flatMap
Adding and removing at either end of an array with push, pop, shift and unshift, building stacks and queues (and why shift gets slow), combining arrays with concat and spread, and flattening nested arrays with flat and flatMap, including flatMap as a map-and-filter in one step.
kvi5hnuCode Sprout team member6 min readOn this page
Arrays in JavaScript double as stacks and queues: four methods add and remove elements at either end. This article covers them, then the methods that combine and flatten arrays: concat, flat and flatMap.

push and pop: working at the end
push(...items) appends one or more elements and returns the new length. pop() removes the last element and returns it, or undefined if the array is empty. Both modify the array in place:
const history = [];
console.log(history.push("open file", "type text")); // new length
console.log(history.pop()); // removed element
console.log(history);
console.log(history.pop(), history.pop()); // empty: undefined
2
type text
[ 'open file' ]
open file undefined
A common slip is using push's return value as if it were the array: const list = [].push(x) makes list a number.
A stack
A stack is last in, first out (LIFO), like a pile of plates. push and pop are exactly that, and both are fast, because nothing else moves. Undo histories, the browser's back button and the call stack itself work this way. A classic interview problem uses one to check brackets:
function isBalanced(text) {
const closers = { ")": "(", "]": "[", "}": "{" };
const open = [];
for (const ch of text) {
if ("([{".includes(ch)) open.push(ch);
else if (ch in closers && open.pop() !== closers[ch]) return false;
}
return open.length === 0;
}
console.log(isBalanced("{ list[i](x) }"), isBalanced("(]"), isBalanced("(("));
true false false
Peek at the top without removing it with stack.at(-1).
shift and unshift: working at the start
unshift(...items) inserts at the start and returns the new length; shift() removes and returns the first element. Every remaining element must move to a new index, so on large arrays these are much slower than push/pop.
const line = ["ana", "bo"];
console.log(line.unshift("vip"), line);
console.log(line.shift(), line);
3 [ 'vip', 'ana', 'bo' ]
vip [ 'ana', 'bo' ]
When you pass several items to unshift, they're inserted as a block, keeping their order, which differs from inserting them one at a time:
const together = [];
together.unshift(1, 2);
const oneByOne = [];
oneByOne.unshift(1);
oneByOne.unshift(2);
console.log(together, oneByOne);
[ 1, 2 ] [ 2, 1 ]
A queue
A queue is first in, first out (FIFO), like a checkout line: add with push, take from the front with shift. Task schedulers, breadth-first search and message buffers are queues.
const jobs = [];
jobs.push("resize photo");
jobs.push("send email");
console.log(jobs.shift(), "| still waiting:", jobs);
resize photo | still waiting: [ 'send email' ]
For a few hundred items, this is perfectly fine. For a queue holding tens of thousands of items, each shift is O(n), so draining it is O(n²). A queue that remembers the position of the head avoids moving elements at all:
class Queue {
#items = [];
#head = 0;
enqueue(item) {
this.#items.push(item);
}
dequeue() {
if (this.#head === this.#items.length) return undefined;
const item = this.#items[this.#head];
this.#items[this.#head++] = undefined; // let the item be garbage-collected
if (this.#head === this.#items.length) { // empty: reset cheaply
this.#items = [];
this.#head = 0;
}
return item;
}
get size() {
return this.#items.length - this.#head;
}
}
const q = new Queue();
q.enqueue("a");
q.enqueue("b");
console.log(q.dequeue(), q.size, q.dequeue(), q.dequeue(), q.size);
a 1 b undefined 0
(Classes and private # fields are part 9. Production code often uses a library deque or a linked list for the same reason.)
Adding many elements: push(...items)
push doesn't flatten an array argument: it pushes the array as one element. Spread it to push its elements:
const target = [1];
target.push([2, 3]);
console.log(target);
const target2 = [1];
target2.push(...[2, 3]);
console.log(target2);
[ 1, [ 2, 3 ] ]
[ 1, 2, 3 ]
Spreading passes every element as a separate function argument, and engines limit how many arguments a call can have. Spreading an array with millions of elements throws a RangeError. For huge arrays, use concat or a loop.
concat: combining arrays
concat(...values) returns a new array: the original elements followed by each argument. Array arguments are flattened one level; other values are added as-is. The original isn't changed:
const base = [1, 2];
const more = base.concat(3, [4, 5], [[6]]);
console.log(base, more);
console.log([...base, 3, ...[4, 5]]); // the spread equivalent
[ 1, 2 ] [ 1, 2, 3, 4, 5, [ 6 ] ]
[ 1, 2, 3, 4, 5 ]
Today, spread syntax is the more common way to combine arrays because it's visually obvious which values get expanded. concat still has advantages: it doesn't hit the argument limit, and it's handy when you don't know whether a value is an array ([].concat(value) turns x into [x] and leaves [x, y] as [x, y]).
flat: flattening nested arrays
flat(depth) (ES2019) returns a new array with nested arrays expanded depth levels deep, 1 by default. Pass Infinity to flatten completely:
const nested = [1, [2, [3, [4]]]];
console.log(nested.flat());
console.log(nested.flat(2));
console.log(nested.flat(Infinity));
console.log([1, , 3].flat()); // holes are removed
[ 1, 2, [ 3, [ 4 ] ] ]
[ 1, 2, 3, [ 4 ] ]
[ 1, 2, 3, 4 ]
[ 1, 3 ]
Flattening an array of arrays (such as the pages of results from an API) into one list is a typical use.
flatMap: map, then flatten one level
flatMap(fn) is map(fn).flat() in one, more efficient step. The callback returns an array for each element, and all those arrays are joined:
const sentences = ["hello world", "good morning"];
console.log(sentences.map((s) => s.split(" ")));
console.log(sentences.flatMap((s) => s.split(" ")));
const orders = [{ id: 1, items: ["pen", "ink"] }, { id: 2, items: ["pad"] }];
console.log(orders.flatMap((order) => order.items));
[ [ 'hello', 'world' ], [ 'good', 'morning' ] ]
[ 'hello', 'world', 'good', 'morning' ]
[ 'pen', 'ink', 'pad' ]
Because the callback can return any number of elements, including none, flatMap can filter and transform in one pass: return [] to drop an element and [value] to keep it.
const inputs = ["42", "abc", "7", ""];
const numbers = inputs.flatMap((s) => {
const n = Number.parseInt(s, 10);
return Number.isNaN(n) ? [] : [n];
});
console.log(numbers);
console.log([1, 2].flatMap((n) => [n, n * 10])); // one element in, two out
[ 42, 7 ]
[ 1, 10, 2, 20 ]
flatMap flattens only one level: returning [[x]] leaves [x] in the result.
Which methods mutate?
| Mutates the array | Returns a new array |
|---|---|
push, pop, shift, unshift | concat, flat, flatMap, spread [...a, ...b] |
Mixing these up is a classic React/Redux bug: calling state.items.push(x) changes the existing state array, so the UI may not notice. Use [...state.items, x] instead.
Common questions
Why does push return the length and not the array?
That's how it was designed in the first version of JavaScript. It means you can't chain push; when you want an expression that returns the new array, use spread: [...arr, x].
How do I remove the first or last n elements?
In place: arr.splice(0, n) (first n) or arr.splice(-n) (last n). As copies: arr.slice(n) and arr.slice(0, -n). Both are covered in the next article.
Is it bad to use shift in loops?
For small arrays, no. For large queues processed item by item, yes: each shift moves every remaining element. Use an index-based queue like the one above, or iterate with for...of and clear the array afterwards.
What's the difference between flat(Infinity) and a recursive flatten function?
None in the result; flat(Infinity) is the built-in version. Writing the recursive one by hand (with reduce and Array.isArray) is still a common interview exercise.
Summary
push/popadd and remove at the end;unshift/shiftat the start. All four mutate;push/unshiftreturn the new length,pop/shiftthe removed element.- A stack is
push+pop(LIFO); a queue ispush+shift(FIFO).shiftandunshiftmove every element, so large queues need a head index. push(...arr)adds an array's elements; very large spreads throwRangeError.concatand spread return a new combined array;concatflattens array arguments one level.flat(depth)flattens nested arrays (Infinityfor all levels) and removes holes.flatMap(fn)maps and flattens one level; returning[]or[x]filters and maps in a single pass.
Practice Questions
What does this print?
const s = [1, 2];
s.push(3);
s.shift();
s.unshift(0);
console.log(s, s.pop());
Answer
[ 0, 2 ] 3. After push the array is [1, 2, 3]; shift leaves [2, 3]; unshift(0) gives [0, 2, 3]. Arguments are evaluated left to right, but console.log prints the array after pop has already removed 3, so it shows [ 0, 2 ].
What does this code return?
[1, [2], [[3]]].concat([4], [[5]]).flat()
Answer
[ 1, 2, [ 3 ], 4, 5 ]. concat flattens its arguments one level, giving [1, [2], [[3]], 4, [5]]; flat() then removes one more level everywhere.
Use flatMap to turn this array into ["a:x", "a:y"]:
[{ name: "a", tags: ["x", "y"] }, { name: "b", tags: [] }]
Answer
items.flatMap((item) => item.tags.map((tag) => `${item.name}:${tag}`))
An item with no tags contributes an empty array and disappears.
Implement a stack-based function reverseWords(sentence) that reverses the order of words.
Answer
const reverseWords = (s) => {
const stack = s.split(" ");
const out = [];
while (stack.length) out.push(stack.pop());
return out.join(" ");
};
In real code, s.split(" ").reverse().join(" ") does the same.
Previous: JavaScript reduce and reduceRight: Summing, Grouping, Counting and Building Objects

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.