JavaScript linked lists: build, reverse, and detect a cycle
Learn JavaScript linked lists: build Node and LinkedList classes, reverse the chain in place with three pointers, unlink from a doubly linked list, detect a cycle with Floyd's two runners, and see when an array still wins.
A JavaScript linked list is a chain of plain objects pointing at each other — the structure behind undo histories, music queues, and the most famous interview question in programming. By the end of this page you will build one with a Node and a LinkedList class, reverse it in place with three pointers, unlink a node from a doubly linked list in two assignments, detect a cycle with Floyd's two runners, and — just as important — know when a boring old array still wins. Every snippet ran on Node 24 and every output is real.
What a linked list is
Think of a treasure hunt. Each clue holds two things: a prize, and directions to the next clue. You never get a map of the whole hunt; you are only told where the first clue is. In code, each clue is a node: a tiny object with a value and a next pointer to the following node. The list itself remembers exactly one thing — the head, where the chain starts. From there you follow next, to next, to next, until a node's next is null. Null means the hunt is over. No slots, no numbering: just objects pointing at each other.
Why bother: prepend is O(1)
Insert at the front of an array and every item already in it has to step one slot to the right before slot 0 is free. A hundred thousand items means a hundred thousand moves, every single time. The linked list does the same job in two pointer moves: make one new node, point its next at the current head, point head at the new node. Nobody else in the chain even notices. It costs O(1) whether the list holds three nodes or three million.
The price shows up when you want something by position. nums[500] in an array is one step — the slots sit side by side and the engine just does the maths. A linked list has no index: there is one way in, at the head, and one way forward, hop by hop. Node 500 is 500 hops; the last node is a walk of the whole chain, O(n). That trade — cheap changes, expensive positions — is the whole story, and the benchmark at the end puts numbers on both sides.
The Node and LinkedList classes
The real thing is shorter than its reputation:
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
}
prepend(value) {
const node = new Node(value);
node.next = this.head;
this.head = node;
return this;
}
append(value) {
const node = new Node(value);
if (!this.head) {
this.head = node;
return this;
}
let last = this.head;
while (last.next) last = last.next;
last.next = node;
return this;
}
toArray() {
const out = [];
for (let node = this.head; node; node = node.next) {
out.push(node.value);
}
return out;
}
reverse() {
let prev = null;
let current = this.head;
while (current) {
const next = current.next;
current.next = prev;
prev = current;
current = next;
}
this.head = prev;
return this;
}
}
const list = new LinkedList();
list.append("a").append("b").append("c");
list.prepend("start");
console.log(list.toArray());
list.reverse();
console.log(list.toArray());
[ 'start', 'a', 'b', 'c' ]
[ 'c', 'b', 'a', 'start' ]
Node is a value and a next that starts as null — a fresh node points nowhere. LinkedList's constructor stores exactly one thing, head, which begins as null: an empty list.
prepend is the star: wrap the value in a node, point the node's next at the current head, crown it the new head. Two pointer moves, O(1), exactly the diagram from the section above. append is the honest one: if the list is empty the new node simply becomes head, otherwise the while loop walks to the last node — the one whose next is null — and hooks the new node onto the end. That walk is what makes a plain append O(n). toArray is the traversal loop every linked list operation is built on: start at head, push each value, step to next, stop at null. Each method returns this, so the calls chain.
Reverse in place: three pointers
Reversing a linked list in place is the classic interview question, because it needs three pointers and zero spare memory. The idea: walk the chain once and turn each arrow around, so instead of pointing forward it points back at the node you just left. The catch is that the moment you flip an arrow, you have lost your road forward — so you keep three fingers on the chain:
prev— the part already flipped (starts asnull, because the first node you flip becomes the tail, and a tail points at nothing).current— the node being flipped right now (starts athead).next— a bookmark that remembers the rest of the chain before you cut it loose.
Each pass of the loop in reverse() above does three things, in an order that matters. Bookmark: const next = current.next saves the road forward before anything is touched. Flip: current.next = prev points this node backwards. Step: prev becomes current, and current becomes the bookmark. When current runs off the end and hits null, every arrow is flipped and head is handed to prev — the old tail. That is why the run above prints [ 'start', 'a', 'b', 'c' ] and then, after one call, [ 'c', 'b', 'a', 'start' ]. One visit per node: O(n), no extra array, no recursion.
Doubly linked lists: next and prev
So far every arrow points one way, which means you can never back up. A doubly linked list gives every node two pointers, next and prev. Your browser's back and forward buttons live on exactly this idea: each page remembers the one before it and the one after it.
The superpower is deletion. In a singly linked list, before you can unlink a node you have to walk from the head just to find who points at it. In a doubly linked list the node already knows both neighbours, so you simply introduce them to each other:
class DoublyNode {
constructor(value) {
this.value = value;
this.prev = null;
this.next = null;
}
}
const a = new DoublyNode("a");
const b = new DoublyNode("b");
const c = new DoublyNode("c");
a.next = b; b.prev = a;
b.next = c; c.prev = b;
a.next = b.next;
c.prev = b.prev;
console.log(a.next.value);
console.log(c.prev.value);
c
a
Two assignments and b is out of the chain: a's next skips ahead to c, c's prev looks back to a. O(1), no walking, no shifting. This is also the classic way to build the deque from the stacks and queues lesson: a doubly linked list is fast at both ends.
Detect a cycle: Floyd's two runners
What happens if some node's next points backwards, at an earlier node? The chain becomes a circle. Nothing crashes — it is sneakier than that: every walk becomes an infinite loop. toArray never finds null, reverse never finishes, your program just hangs.
Floyd's cycle detection — the tortoise and the hare — finds the circle without walking forever. Put two runners on the chain: slow hops one node at a time, fast hops two. If the chain has an end, fast reaches null and there is no cycle. If the chain is a circle, fast comes around behind slow and catches him, the way a sprinter laps a jogger on a running track. The moment both runners stand on the same node, the loop is proved.
function hasCycle(head) {
let slow = head;
let fast = head;
while (fast && fast.next) {
slow = slow.next;
fast = fast.next.next;
if (slow === fast) return true;
}
return false;
}
const a = { value: "a", next: null };
const b = { value: "b", next: null };
const c = { value: "c", next: null };
a.next = b;
b.next = c;
console.log(hasCycle(a));
c.next = a;
console.log(hasCycle(a));
false
true
The while condition is the safety rail: fast must exist, and so must fast.next, otherwise fast.next.next would crash at the end of a normal list. The comparison is === on the nodes themselves — it asks whether slow and fast are literally the same object, not whether two values look alike. The test builds three plain object nodes (a node doesn't need a class, just value and next), gets false on the straight chain, then one line — c.next = a — closes the circle and the same chain reports true. Hand it an empty list and head is null, the loop never starts, and it calmly returns false.
The honest benchmark: when an array wins
Both trades, same machine, one run, measured with console.time:
const N = 100_000;
console.time("array unshift");
const arr = [];
for (let i = 0; i < N; i++) arr.unshift(i);
console.timeEnd("array unshift");
console.time("list prepend");
let head = null;
for (let i = 0; i < N; i++) head = { value: i, next: head };
console.timeEnd("list prepend");
console.time("array read item 50000, x1000");
let a = 0;
for (let i = 0; i < 1000; i++) a += arr[50_000];
console.timeEnd("array read item 50000, x1000");
console.time("list read item 50000, x1000");
let b = 0;
for (let i = 0; i < 1000; i++) {
let node = head;
for (let k = 0; k < 50_000; k++) node = node.next;
b += node.value;
}
console.timeEnd("list read item 50000, x1000");
array unshift: 726.99ms
list prepend: 3.187ms
array read item 50000, x1000: 0.019ms
list read item 50000, x1000: 68.421ms
A hundred thousand inserts at the front: unshift took about 727 ms, because every insert shuffles everything after it; the list prepend took about 3 ms — a couple of hundred times faster. Then the other direction: reading item 50,000 a thousand times took 0.019 ms in the array (index maths, one jump per read) and 68.4 ms in the list, thousands of times slower, because every single read walks 50,000 hops. (Timings vary by machine; the shape of the gap doesn't.)
And day to day, arrays win even more often than that: their items sit next to each other in memory, so plain loops run faster, and V8 has spent twenty years tuning them. The rule: reach for a linked list when the work is constant inserting and removing at the ends, or mid-chain with the node already in hand. Reach for an array for everything else.
What you learned
- A linked list is nodes — a
valueplus anextpointer — chained fromheadtonull; no slots, no index. prependis two pointer moves, O(1); anything by position is a hop-by-hop walk, O(n); a plainappendis O(n) because it walks to the end.- Reverse in place is the three-pointer walk — bookmark, flip, step — one visit per node, no extra memory.
- A doubly linked list adds
prevand unlinks a node in two assignments, O(1). - Floyd's two runners (
slowone hop,fasttwo) detect a cycle before your loop hangs forever; the check is===on the nodes themselves. - In one real run: the list won 100,000 front inserts 727 ms to 3 ms, and the array won reading item 50,000 by thousands of times — a linked list is a specialist's tool, not a default.
Common questions
Does JavaScript have a built-in linked list? No. Unlike Java's LinkedList, JavaScript ships nothing — but it needs nothing either: a node is just an object with value and next, as the hasCycle test shows. The 50-line class on this page is the whole structure.
Why is my reverse() losing nodes? Almost always the order inside the loop. The bookmark line — const next = current.next — must run before the flip current.next = prev; flip first and the rest of the chain is unreachable. And the new head is prev after the loop, not current (which is null by then).
Why does hasCycle check fast && fast.next? Because fast jumps two nodes with fast.next.next. On a normal list fast eventually lands on the last node (fast.next is null) or runs past it (fast is null); either way, reading .next.next without the guard throws TypeError: Cannot read properties of null. The guard makes both endings exit the loop cleanly with false.
When should I actually use a linked list in JavaScript? When the work is constant inserting or removing at the ends or mid-chain with the node already in hand: queues and deques, LRU caches, undo chains. For reading by index, searching, or plain loops over data, an array is faster — often by a lot, as the benchmark shows.
Isn't unshift fast enough in practice? For a handful of items, yes. The 727 ms in the benchmark is 100,000 unshifts in a loop — O(n) each, O(n²) in total, the same trap as shift() in the stacks and queues lesson. If front inserts happen inside a loop that can grow, use a list (or build backwards and reverse once).
Next lesson: recursion — a function that calls itself, the call stack drawn so you can finally see it, and why one missing stop condition crashes your program with a stack overflow.
This article goes with the video JavaScript Linked Lists: Build, Reverse, Detect a Cycle. Watch it on YouTube.