Linked Lists in JavaScript, simplified

Sarah Larkworthy
2 min readSep 1, 2020

--

JavaScript doesn’t have a lot of the built-in data structures that other languages like Java have, so it can be tricky to know how to utilize them in JavaScript, if that is your current language of choice. This post is meant to demystify the modern JavaScript linked list in a way that makes sense for interviews and quick problem-solving.

For a brief review, linked lists are a data structure in which each node contains a value and points to one other node. It ends on a node that points to null instead of another node.

1 — > 2 — > 3 — > 4 — > null

In order to use linked lists, you could make your own linked list class, and then your own node class, and pad your linked list class out with every method under the sun. But there’s an easier way:

class Node {
constructor(value, next=null){
this.value = value;
this.next = next;
}
}

Using this Node class build, creating a new linked list is as easy as this:

let root = new Node(1);
root.next = new Node(2);
root.next.next = new Node(3);
root.next.next.next = new Node(4);

The fourth node will automatically point to null, as that is what the “next” parameter default value is.

Now you have a quick way to create a Linked List when asked to do something like reverse a linked list in place:

function reverse(head) {
let current = head;
let previous = null;
while (current) {
temp = current.next;
current.next = previous;
previous = current;
current = temp;
}
return previous;
}

I hope this helps demystify Linked List problems when using JavaScript!

--

--