Building a linked list in Javascript with pointers

After implementing a linked list in two different ways using Javascript, I found myself in a state of confusion about the inner workings of the code.

Trying to mentally visualize the creation process and the memory addresses being referenced proved to be a challenging task, especially considering the concept of passing by reference.

  • Are both implementations technically correct?
  • Although they appear to achieve the same results, do they operate differently under the surface?
  • In the first option, specifically in the prepend() method, a new object is created in memory where the "next" property points to the existing memory address of the "head" property, while the "head" property is then pointed to the newly created object. At a glance, it might seem like a circular reference, but somehow it still works. How is this possible?

The key variations lie within the append() and prepend() methods.

Option 1:

class myLinkedList {
    constructor(value) {
    this.head = {
      value: value,
      next: null
    }
    this.tail = this.head;
  }
  
  append(element){
    this.tail.next = {
      value: element,
      next: null
    }
    this.tail = this.tail.next;
  }

  prepend(element) {
    const newObj = {
      value: element,
      next: this.head
    }
    this.head = newObj;
  }
}


const linkedList = new myLinkedList(1);
linkedList.append(2);
linkedList.prepend(0);

Option 2:

class myLinkedList {
    constructor(value) {
    this.head = {
      value: value,
      next: null
    }
    this.tail = this.head;
  }
  
  append(element){
    const newNode = {
      value: element,
      next: null
    }
    this.tail.next = newNode;
    this.tail = newNode;
  }

  prepend(element) {
    const newNode = {
      value: element,
      next: null
    }
    newNode.next = this.head;
    this.head = newNode;
  }
}

const linkedList = new myLinkedList(1);
linkedList.append(2);
linkedList.prepend(0);

Answer №1

You provided further clarification in the comments section.

The explanation pertains to the concept of variable binding versus values in JavaScript.

JavaScript utilizes internal representations for various data types such as strings, numbers, and user-defined objects. These representations remain consistent regardless of whether the value is named foo or is deeply nested within a data structure.

Variables in programs are associated with specific values at any given moment. This mechanism enables programmers to dictate the behavior of the values they are bound to in JavaScript.

Assignment involves binding values to entities. When a variable is assigned a new value, it severs its previous link to any older value it may have been bound to. The old value might still exist within a data structure or could be marked as garbage for disposal. Nevertheless, it is no longer directly linked to that variable.

The provided sample code demonstrates this process.

-- Define a value and bind it to 'head'.
let head = {
    value: 2,
    next: null
};
/* CURRENT BINDING:
 *
 *    head ----> {value:2, next:null}
 */

-- Establish a value and bind it to 'newObj'.
let newObj = {
    value: 1,
    next: head
};
/* CURRENT BINDING:
 *
 *  newObj ----> {value:1, next:
 *    head ---->     {value:2, next:null}
 *               }
 */

-- Reassign the variable 'head' to the value that 'newObj' is linked to.
head = newObj;
/* CURRENT BINDING:
 *
 * head,newObj
 *         ----> {value:1, next:
 *                   {value:2, next:null}
 *               }
 */

-- Confirm that the reassignment was successful.
console.log(head)

Does this explanation help clarify your understanding of how programs manage data and why the provided code does not create a circular reference?

If you're interested, circular references can be intentionally created as well.

let foo = {value:1};
foo['next'] = foo;
console.log(foo);

You might wonder how this works, considering assignment simply binds values to entities. While this is true, if the entity being bound to already exists within a data structure, the structure itself must be modified to accommodate the new binding.

The consequences of creating circular references vary across programming languages. In JavaScript, the garbage collector eventually removes unreferenced objects. On the other hand, in Python, this situation can lead to memory leaks. Each language handles circular references uniquely.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Arranging array absolute values efficiently using Java in less than O(n^2)

Is there a way to efficiently output the elements of a sorted array, containing both positive and negative numbers, based on their absolute values without using any built-in functions? For example, an array like -9, -7, -4, -0.9, 1, 2, 3, 8. Does anyone h ...

Troubleshooting: ngAnimate max-height failing to apply to specific element

Having integrated ngAnimate into a project to enhance animations, I've encountered some unusual behavior with a specific element. Let me provide some context: our website features a shop with categories and products within those categories. I am usin ...

Display a preview of a React component

Currently facing a challenge where I need to create a form for users to adjust the title, background color, button background, text color, and other settings of a component. I want to provide a live preview of the component as the user makes changes. I en ...

What HTML element can be used outside of a Bootstrap dropdown item to show a default image when the dropdown is open?

I'm working on my menu where I have two columns - one for submenu text and the other for respective images. Everything is working fine so far. However, I want to set a default image that will display when the user does not hover over any dropdown item ...

Customizing the appearance of a data field in Angular-ui-grid: Tips and tricks

In my quest through the angular-ui-grid documentation, I have been unable to locate any mention of "CellFormatters" which were utilized in a previous project a few years back. The purpose of the "CellFormatters" was to present a text representation of the ...

What could be the reason for my CORS headers not aligning even though they appear to be identical?

I encountered an issue while using passport js with REACT. When trying to fetch the logged in user data, I faced a problem where the cors header of fetch didn't match even though they are identical. Here is the endpoint I am sending the fetch request ...

Streamlining programming by utilizing localStorage

Is there a more efficient way to streamline this process without hard-coding the entire structure? While attempting to store user inputs into localStorage with a for loop in my JavaScript, I encountered an error message: CreateEvent.js:72 Uncaught TypeErr ...

How can the value of a number in Angular be changed without altering its original value?

Imagine having the initial number 100. If I enter 50 in another input, it should add 50 to 100. However, if I then change the value from 50 to 80, the total should be 180 and not 230. The goal is always to add numbers to the original sum, not the new valu ...

Leverage JavaScript libraries utilizing namespaces within your Angular application

I have a unique JavaScript library that includes functions organized within namespaces. For example: var testNamespace = { insideFunction: function(str) { alert(atr); } }; Now, I am trying to integrate these functions into my Angular app.c ...

Locate the user, repository, and file path within a GitHub URL

How can I extract the user, repo, and path from a Github URL pasted into a form in order to make API requests? For example, https://github.com/HubSpot/BuckyClient/blob/master/README.md I have started working on a regex solution to locate the different par ...

Divinely favored - pay attention for each and every sound

Currently, I am utilizing node with the blessed tty library downloaded from NPM. Within this library, there is a method called "key" that I am using in the following way: blessed.key(['q', 'z'], function(ch, key) { //do something ...

Error occurred while deserializing an XML collection in C# due to a nested collection being null

I have been working with a third-party API and faced a challenge while deserializing an XML string into C# complex classes. The issue arises when trying to deserialize a nested array within an array. Although I have successfully serialized the outer List ( ...

Changing the data request body in datatables ajax on button click

My goal is to initially fetch data when the page loads and then allow users to apply filters by clicking on them to fetch updated data. The query I am using is a POST request because it requires complex parameters that need to be formatted as JSON for bett ...

The modal form vanishes without any action when the form is clicked outside

Everything was working fine with the form submission until I turned it into a modal using Bootstrap. Now, when the form is rendered in the modal, users can tab and type without any issues. However, if they click on any element within the modal (including t ...

How to use Angular pipes to format dates as Long Dates in the template

Suppose I have a date input such as 2022-04-02T00:00:00. When I utilize {{data?.dateStarted | date:'MM/dd/YYYY'}}, the result will be 04/02/2022. But how can we transform it into a Long Date format like April 2, 2022? Does anyone have any sugges ...

The React.useCallback hook in Cube.js is missing a dependency, specifically 'pivotConfig'. This could potentially cause unexpected behavior in the application

After multiple attempts at creating a straightforward dashboard using Cube.js with Windows 10 and MySQL version 8, I am feeling frustrated. Initially, I experimented with a JavaScript backend, struggled through the installation process for days, then attem ...

The variable is unable to be accessed within the PHP function query

After passing a variable through ajax to a function within my php file "Cart_code.php", I encountered an issue where the variable was not accessible inside the function. Can you help me figure out why? Javascript $.ajax({ type: "POST", url: "incl ...

Using jQuery to toggle visibility based on data equivalence

I created a code snippet in which I am implementing jQuery show/hide functionality when the data attribute matches. Here is the HTML structure: <div class="container"> <div class="item" data-item="1">1 <div class="inside" data-c ...

Issue: $injector:unpr Unrecognized Provider DataServiceProvider (a provider that has not been defined before)

Encountering this issue: Error: [$injector:unpr] http://errors.angularjs.org/1.5.6/$injector/unpr?p0=DataServiceProvider%20%3C-%20DataService%20%3C-%20SignupController Suspecting that the problem lies in the fact that DataService cannot be found due to ...

Exploring the world of jQuery AJAX requests by sending POST data to a PHP

I am currently in the process of building a cross-platform application utilizing HTML, CSS, and jQuery/JavaScript. My approach involves using AJAX requests to retrieve data from a database and send data to it as well. I have successfully implemented the &a ...