πŸš€ Frontend DSA 5 - πŸ“Š How to Sum Values in a Singly Linked List in JavaScript (Recursive Approach)

Singly linked lists are a fundamental data structure every JavaScript developer should understand. They’re used in everything from memory-efficient data storage to implementing queues and stacks. πŸš€

In this article, you'll learn how to traverse and sum all values in a singly linked list using a recursive approach in JavaScript. 🧠


πŸ“Œ What’s a Singly Linked List?

A singly linked list is a collection of nodes where:

  • Each node has a value.
  • Each node has a reference (pointer) to the next node.
  • The last node's next is null.

Example:

1 β†’ 2 β†’ 3 β†’ 4 β†’ null

Each node "points" to the next, just like a chain πŸ”—.


🧠 Problem: Calculate the Total Sum of All Values in the Linked List

You’re given a linked list:

let list = {
  value: 1,
  next: {
    value: 2,
    next: {
      value: 3,
      next: {
        value: 4,
        next: null
      }
    }
  }
};

Problem Statement

You need to write a function that sums all the values in the list and returns the total βž•.


βœ… JavaScript Recursive Solution

// πŸ“Œ Function to calculate sum of linked list values recursively
const printList = (inputList) => {
    // πŸ›‘ Base case: If no next node, return current node's value
    if (inputList.next === null) {
        return inputList.value;
    } else {
        // πŸ” Recursive case: Add current value to sum of rest of list
        return inputList.value + printList(inputList.next);
    }
};

Code Block


πŸ”’ Sample Input and Output

πŸ§ͺ Example 1

let list1 = {
  value: 1,
  next: {
    value: 2,
    next: {
      value: 3,
      next: {
        value: 4,
        next: null
      }
    }
  }
};

console.log(printList(list1)); // βœ… Output: 10

Code Block


πŸ§ͺ Example 2

let list2 = {
  value: 5,
  next: {
    value: 10,
    next: {
      value: 15,
      next: null
    }
  }
};

console.log(printList(list2)); // βœ… Output: 30

Code Block


πŸ§ͺ Example 3

let list3 = {
  value: 42,
  next: null
};

console.log(printList(list3)); // βœ… Output: 42

Code Block


🧠 JavaScript Notes

  • Recursion is when a function calls itself. In our case, each function call processes one node and passes the rest down.
  • The base case (if(inputList.next === null)) ensures the recursion stops.
  • This function returns a sum, not logs β€” great for unit tests! βœ…
  • Works well for small to medium-sized lists. For very large lists, consider an iterative version to avoid a stack overflow. ⚠️

πŸ”„ Iterative Version (Bonus)

const printListIterative = (inputList) => {
  let sum = 0;
  let current = inputList;
  
  while (current !== null) {
    sum += current.value;
    current = current.next;
  }

  return sum;
};

Code Block


✨ Final Thoughts

Learning to work with linked lists is πŸ”‘ for improving your data structure and algorithm skills in JavaScript. Whether you're preparing for interviews or building custom data models, recursive and iterative traversal will always be handy.

πŸ§‘β€πŸ’» Want to visualize the list traversal or convert this to a doubly linked list? Let me know β€” we’ll break it down step by step!


Hey there from LearnYard! πŸ‘‹

Glad to see you exploring the free content from our course! We’ve shared 10 valuable articles at no cost to help you get a real feel of what’s inside.

If you’ve found these helpful, we’d love to know! πŸ’¬
Share your thoughts or key takeaways on LinkedIn, Twitter, or Instagram β€” and don’t forget to tag Gourav Hammad & Mohammad Fraz. We’ll personally respond to your post!

Thanks for being part of the LearnYard journey. Keep learning, keep growing! πŸš€


Loved the free content? Want access to the full course β€” for free? πŸ’Έ

Share the course with your friends using your affiliate link (you’ll find it on your profile or home page), and earn 20% commission on each sale.

Just 4–5 sales and you’ll recover the full course price of your course πŸ”
So why wait? Start sharing, start earning, and unlock the rest of the course effortlessly! πŸ› οΈπŸ“ˆ


πŸ“š Keywords for SEO

  • JavaScript Linked List Sum Example
  • Recursively Traverse a Linked List in JavaScript
  • Singly Linked List Recursion in JavaScript
  • How to Sum Nodes in a Linked List Using JavaScript
  • Beginner’s Guide to Data Structures in JavaScript
  • Linked List Implementation in JavaScript
  • Recursive Function to Sum Linked List Nodes
  • Understanding Recursion with Linked Lists in JS
  • JavaScript Data Structures Tutorial
  • Linked List Basics for JavaScript Beginners

πŸ“’ Hashtags for Visibility

#JavaScriptDataStructures #LinkedListJS #RecursionInJS #FrontendInterviewPrep #LearnJavaScript #SinglyLinkedList #JSForBeginners #CodeNewbie #DSAwithJavaScript #JavaScriptRecursion #FrontendMasters #TechLearning #CodingChallenges #JSAlgorithms #SumLinkedList #RecursiveJS #WebDevelopment #InterviewPreparation #FunctionalProgrammingJS #JavaScriptEssentials