How To: Build a Linked List in JavaScript
Tags: javascript, algorithms, datastructures, beginners
Published: 2022-01-03 19:16:11

:cloud: Hi Programmers! :cat:

Today we will be building a Linked List from scratch using JavaScript. If you are not familiar with Linked Lists, please head over to [this](https://dev.to/am20dipi/what-is-a-linked-list-4p1d) article first and then join us after :)

Let's get started. 
_________________________________________________

### Goals

1. [Classes in JavaScript](#classes)
2. [Class Syntax & the Constructor](#constructor)
3. [Declaring the LinkedList Class](#linked-list)
4. [Building LinkedList's Constructor Method](#linked-con)
5. [Instantiating a New Instance of LinkedList](#instantiate)

_________________________________________________

## Classes in JavaScript <a name="classes"></a>

**JavaScript actually does not have linked lists built in.** However, JavaScript, being as powerful and flexible as it is, is capable of building linked lists using ES6 **class** syntax. 

As you may or may not know, JavaScript classes are **syntactic sugar**: meaning classes are not necessarily something _brand new_. Classes should be thought of as a **blueprint** for a JavaScript object. So, when you hear the term "syntactic sugar," think Classes make the code cleaner, more accessible and more readable. 

Since classes are "blueprints," classes do a lot of describing. Classes will describe what the object should do (methods) and what the object has (properties). 

Classes are sweet (like _syntactic sugar_) because each instance of the JavaScript object created out of the class will have **the same properties and methods!** This is amazing. This reduces a whole lot of code needed to be written and needed to be considered. 

Ok - you may have guessed by now... today we will be using Class syntax to build our Linked List!

_________________________________________________

## Class Syntax & the Constructor() <a name="constructor"></a>

One way to define a class is using a <strong>class declaration</strong>. To declare a class, you use the <strong>class keyword</strong> with the name of the class.

Here is an example:

```js
class Post {

}
```
That's it! That's a class declaration. Now, there are some important AND essential aspects we need to include in our class to make it functional as a blueprint of an object: 

- constructor method
- properties
- methods

While the first one may be unrecognizable to you, both **properties** and **methods** should be familiar since JavaScript objects have both properties and methods. 

The **constructor method** is used to create a new instance of our class. (THINK: The constructor method _constructs_ a new instance.) While instances of a class can be instantiated with no properties or methods, that would be silly. Classes are amazing for just that! So, the constructor method holds the class's properties and methods and when a new instance is created by the constructor method, that instance has access to those properties and methods.

Let's see this in our example class "Post":

```js
class Post {
   constructor(title, author){
      this.title = title;
      this.author = author;
      this.created_at = new Date()
   }
}
```
An instance of our Post class when instantiated will have a title property, an author property and a created_at property. And every instance of Post instantiated from here on out will too!

Now we are familiar with class syntax and the functionality of a constructor method, let's start this linked list build!

_________________________________________________


## Declaring the LinkedList Class <a=name"linked-list"></a>

Knowing what we know, let's declare a class called "LinkedList" since that is what we are building:

```js

class LinkedList {

}
```

**_Class names will start with a capital letter and designate a new word by using another capital letter. No spaces!_**

_________________________________________________


## Building LinkedList's Constructor Method <a=name"linked-con"></a>

Onto the constructor method, we need each instance of a LinkedList to have specific things that are characteristic of a linked list:

**1.** Head (consisting of data, pointer)
**2.** Tail (consisting of data, pointer)
**3.** Length

Every linked list has a **head** representing the first node; a **tail** representing the last node; and a **length** representing how many nodes are in the linked list. 

```js
class LinkedList {
    constructor(){
        this.head = 
        this.tail =
        this.length =
    }
}
```

_**This** keyword refers to the instance instantiated._

Since both the head and the tail are nodes, and we know that **nodes consist of both data and a pointer to the next node**, we need to show that in the constructor. 

```js
class LinkedList {
    constructor(){
        this.head = { 
            data: ___,
            pointer: ___,
        }
        this.tail = { 
            data: ___,
            pointer: ___,
        }
        this.length = ___
    }
}
```

By passing in "data" into the constructor, we can set a node's data to the data passed in.

```js
constructor(data){
        this.head = {
            data: data,
            pointer: ___
        }
```

Regarding the pointer of the head node, its value will be _null_. **The reason is that when we instantiate a new instance of a LinkedList, there is only one node** AND the tail node **always points to null**! 

Therefore, technically, our tail node is our head node and our length is 1.

```js
class LinkedList {
    constructor(data){
        this.head = {
            data: data,
            pointer: null
        }
        this.tail = this.head
        this.length = 1
    }
}
```

_________________________________________________

## Instantiating a New Instance of LinkedList <a name="instantiate"></a>

Let's see this in action. 

**1.** In your console, paste the above code snippet from the above section and click 'enter'. 

**2.** Then declare and assign a new instance of LinkedList to a constant called 'newLinkedList' and pass a string ('I love data structures') to LinkedList -- this string represents our data. 

**3.** Call 'newLinkedList'. 


![linked list](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/957u3cknm933jjjqgv04.png)
 
It works! If we expand 'newLinkedList', we should see the head, the tail and the length: 

![new linked list](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lim2fb5md38cxxgjvtv5.png)

Nice! 

_________________________________________________

## Recap + Summary <a name="recap"></a>

You may notice our instance of LinkedList only has one (1) node. That is true. I plan on writing another blog soon focusing on how to append, prepend and delete nodes from a linked list. So, stay tuned. 

Today's linked list is a simple one. But it is a great starting point for understanding the foundation of a what a linked list is and also understanding how powerful JavaScript is. 

_So, let's continue to learn together and soon enough, we can teach others._

As always, please feel free to comment, ask questions or make suggestions. 

Follow for more articles and befriend me on LinkedIn too :) 

:white_heart::white_heart::white_heart:
:cat::cat::cat: