Creating linked list using JavaScript objects

Sunday, Jan 12, 2020
JavaScript DataStructures

Linked lists can be better choice when changing the data is a more frequent operation than accessing the data. For example, let's say sales data for a company has to be updated every day while sales report is generated only once a month.

Advantages of Linked List

Some downsides

Creating linked list

Linked list consist of nodes where each node has two pieces of information, 1) the data stored in the node and 2) pointer to the next node. This is a good fit for object implementation. We will also create a function that can be used to append an item to the end of the list (noting that the last node always points to null).

After defining the constructor, we can define methods associated with the constructor using protoype keyword in function definitions. The append method in the following example is creating using this approach.

// linked.js -- implementing linked-list in JavaScript
function LLNode(data){ = data; = null;

var head = new LLNode();  // declare an empty linked list

LLNode.prototype.append = function(x) // writing method for LLNode using prototype
    if ( == undefined) // if empty, set head to x
    { = x;
    var tmp = head;
    while ( != null)
        tmp =; = new LLNode(x);

head.append(33); // calling append method on head


LLNode { data: undefined, next: null }
LLNode {
  data: 33,
  next: LLNode { data: 64, next: LLNode { data: 69, next: null } }