How To Do Singly Linked Lists in JavaScript

Introduction

This is a series where you will learn about singly linked lists in JavaScript, doubly linked lists, stacks, and queues.

The other links Are Here:

  • How To Do Singly Linked Lists in JavaScript (This post)
  • How To Do Stacks in JavaScript (Coming Soon)
  • How To Do Doubly Linked Lists in JavaScript (Coming Soon)
  • How To Do Queues in JavaScript (Coming Soon)

What is a Linked List?

A linked list is an abstract concept in which you have a “node” object that references the next object (which is a property within that node) and has a value property. The object would look something like this:

{
  value: 10,
  next: {...} // This would be another object
}

Imagine these objects linked together in a chain, and then you have the top object. This top level is called the head (or sometimes referred to as the top).

Linked lists show data in a linear fashion. A great example of this would be the back and forwards on your web browser. While in a web browser you have another pointer to previous, it is still the same concept.

Linked lists can also be used in other abstract data types such as stacks and queues.

How-To

Now that you know what these are (sort-of) and what they are useful for, you can now learn the basic implementation of a linked list. It’s possible to create objects and just use it that way, but the simplest way to represent these in the end would be in something like object oriented JavaScript with classes.

Here’s an example of a node class:

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

With this Node class, I can create an instance of node which will hold the two values that make up a linked list. Think of it like a chain that you would use to pull a trailer or strap down something large. Each Node is like a link, and they all are unique.

Conclusion

In the next post, we will use this Node class to create a stack. (Think of a stack like dishes).