Linked Lists
The train’s of Javascript
Have you ever gotten on a train in the first car and had to walk car by car in order to find your friend? I hope so because that is how searching for data works while using linked lists in Javascript. Before I describe how searching for data works, lets do over what a link list looks like and how it functions.
Linked lists are like trains. The first car, is called a “head” while the last car is called a “tail”. If the train only has one car, it is both the “head” and the “tail”. Each car is called a “node”. “Nodes” are also objects!
Instead of having seats, our train contains only two pieces of data:
- The data
- The next node on the list or car on the train.
If there is no node afterwards, the next value points to null, like this… next : null
Now that you know what a head, tail and node are, lets discuss manipulating the list.
Get Judah Lamm’s stories in your inbox
Join Medium for free to get updates from this writer.
Finding Nodes
- Start at the head (not possible to jump to the middle/end cars without walking through each car)
- If the value in the current node does not match what you are looking for, move on to the next node.
- Rinse and repeat
Deleting nodes
- Find the node you want to delete
- Update the previous nodes next statement (previous.next) to point to the node on the list that is AFTER the node you want to delete (previous.next = current.next)
Adding in nodes (to the end/tail)
- Set the next value (next : null) on the tails node to your new node
- Set the next value on the node you are adding (new node name.next) to null. This is make it the new tail, as it does not point to any new nodes.
Inserting nodes (to the head or in the middle)
- Get the location in your list where you want to add your node into. (current node.next)
- Set the next value in your current node to the name of your new node (current node.next = new node)
- For the new node you are inserting, set its next value to the value of the next node. (new node.next = the next node.next)
Now that you know what a linked list is, what it consists of and how to manipulate it, why do you use it? If you have some data, but are unsure of how large it could grow and you want it to know its order, linked lists are the way to go! Knowing the order and being able to change it, while still being able to keep track of where it is moving to is a major advantage of linked lists.






