Skip to content
the poor coder

how to iterate through linked list javascript

Poor Man
Published
Reading time
1 min read
On this page

How to Iterate Through Linked List in JavaScript#

If you are working with linked lists in JavaScript, you may need to iterate through the elements of the linked list. Here are a few ways to do it:

1. Using a While Loop#

One common way to iterate through a linked list is to use a while loop. Here is an example:

Text

    let currentNode = head;
    while(currentNode) {
      console.log(currentNode.value);
      currentNode = currentNode.next;
    }
  

In this example, we start at the head of the linked list and loop through each node until we reach the end of the linked list (when currentNode is null).

2. Using a For Loop#

You can also use a for loop to iterate through a linked list. Here is an example:

Text

    for(let currentNode = head; currentNode; currentNode = currentNode.next) {
      console.log(currentNode.value);
    }
  

In this example, we use a for loop to loop through each node in the linked list. The for loop is essentially the same as the while loop, but it is more concise.

3. Using Recursion#

Another way to iterate through a linked list is to use recursion. Here is an example:

Text

    function iterateLinkedList(node) {
      if(node) {
        console.log(node.value);
        iterateLinkedList(node.next);
      }
    }
    iterateLinkedList(head);
  

In this example, we define a recursive function called iterateLinkedList that takes a node as a parameter. The function checks if the node is null, and if not, it logs the value of the node and calls itself with the next node in the linked list.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC