🧮 JavaScript Data Structures & Algorithms
Estimated reading: 5 minutes 10 views

🧱 JavaScript – Data Structures: List, Graph & Tree Explained with Examples


🧲 Introduction – Why Learn Data Structures in JavaScript?

Ever wondered how complex apps like Google Maps or Facebook manage their data so efficiently? The answer lies in data structures. Whether you’re storing a simple list of items or managing millions of interconnected users, choosing the right data structure is essential for performance, scalability, and logic.

By the end of this guide, you’ll understand:

✅ What Lists, Trees, and Graphs are
✅ How to implement them in JavaScript
✅ Real-world use cases for each
✅ Common operations and best practices

Let’s break these down with code and visuals!


📋 1. JavaScript Lists (Arrays & Linked Lists)

📌 What is a List?

A list is an ordered collection of elements. JavaScript offers native support for lists via arrays, but linked lists can also be implemented manually for more control over memory and performance.


🔢 JavaScript Arrays

const fruits = ['🍎', '🍌', '🍇'];
fruits.push('🍍');
console.log(fruits); // ['🍎', '🍌', '🍇', '🍍']

Explanation:

  • ['🍎', '🍌', '🍇'] → creates an array (a list of elements).
  • .push('🍍') → adds an item to the end.
  • Arrays support indexing, iteration, sorting, and more.

💡 Use When: You need fast access to items using indices (O(1) access).


🔗 Singly Linked List Implementation

class Node {
  constructor(data) {
    this.data = data;
    this.next = null;
  }
}

class LinkedList {
  constructor() {
    this.head = null;
  }

  append(data) {
    const newNode = new Node(data);
    if (!this.head) return this.head = newNode;
    let current = this.head;
    while (current.next) current = current.next;
    current.next = newNode;
  }

  print() {
    let current = this.head;
    while (current) {
      console.log(current.data);
      current = current.next;
    }
  }
}

const list = new LinkedList();
list.append("A");
list.append("B");
list.print(); // A B

Explanation:

  • Node holds data and a pointer (next) to the next node.
  • LinkedList.append() adds a new node to the end.
  • print() traverses and logs each node.

⚠️ Note: Linked lists are better for frequent insertions/deletions compared to arrays.


🌳 2. JavaScript Trees

📌 What is a Tree?

A tree is a hierarchical structure where each node has a parent and zero or more children. Trees are used in DOM, file systems, search engines, etc.


🌲 Binary Tree Example

class TreeNode {
  constructor(value) {
    this.value = value;
    this.left = null;
    this.right = null;
  }
}

const root = new TreeNode(10);
root.left = new TreeNode(5);
root.right = new TreeNode(15);

Explanation:

  • Each node holds a value and two children: left and right.
  • This is a binary tree (each node has max 2 children).

🔍 In-order Traversal

function inorder(node) {
  if (!node) return;
  inorder(node.left);
  console.log(node.value);
  inorder(node.right);
}

inorder(root); // Output: 5 10 15

Explanation:

  • Recursively visits the left subtree, current node, and right subtree.
  • Useful for sorted traversal of binary search trees.

💡 Use When: Representing hierarchies (e.g., DOM, organization charts, nested comments).


🔗 3. JavaScript Graphs

📌 What is a Graph?

A graph is a collection of nodes (vertices) and edges that connect them. Graphs are used in social networks, recommendation engines, routing systems, and more.


🧭 Graph Implementation (Adjacency List)

class Graph {
  constructor() {
    this.adjacencyList = {};
  }

  addVertex(vertex) {
    if (!this.adjacencyList[vertex]) this.adjacencyList[vertex] = [];
  }

  addEdge(v1, v2) {
    this.adjacencyList[v1].push(v2);
    this.adjacencyList[v2].push(v1); // undirected
  }

  display() {
    for (let vertex in this.adjacencyList) {
      console.log(`${vertex} -> ${this.adjacencyList[vertex].join(', ')}`);
    }
  }
}

const g = new Graph();
g.addVertex("A");
g.addVertex("B");
g.addVertex("C");
g.addEdge("A", "B");
g.addEdge("A", "C");
g.display();

Explanation:

  • adjacencyList stores vertices and their neighbors.
  • addEdge() connects two nodes.
  • display() prints connections.

🧠 Graph Types:

TypeDescription
DirectedEdges have direction
UndirectedEdges go both ways
WeightedEdges have weights/costs
UnweightedEdges are equal in value

🔄 Comparing Lists vs Trees vs Graphs

FeatureListTreeGraph
StructureLinearHierarchicalNetwork/Connected
Cycles Allowed❌ No❌ No (in general trees)✅ Yes
Search TimeLinear (O(n))Logarithmic (O(log n))Varies (O(V+E))
Best Use CaseOrdered dataDOM/File SystemNetworks, Social Connections

📘 Best Practices

  • ✅ Choose arrays for indexed or ordered data access.
  • ✅ Use linked lists for dynamic memory allocation or frequent insertions.
  • ✅ Use trees for hierarchical models.
  • ✅ Use graphs when relationships are non-hierarchical (networks).

📌 Summary

In this guide, we covered the fundamentals and differences between:

  • Lists (arrays and linked lists)
  • Trees (binary and hierarchical)
  • Graphs (nodes and edges)

Each has unique strengths and is suited for different problem domains. Mastering these structures will significantly improve your problem-solving and application logic.


❓FAQs – JavaScript Data Structures

What’s the difference between a tree and a graph?
➡️ A tree is a type of graph with no cycles and a single root. Graphs can have cycles and don’t need a root.

Are arrays and lists the same in JavaScript?
➡️ In JavaScript, arrays are the built-in implementation of lists, but you can build more advanced lists like linked lists manually.

Why implement a linked list manually in JavaScript?
➡️ Linked lists allow for faster insertions/removals in large data structures where resizing arrays is costly.

When should I use a graph in JavaScript?
➡️ Use graphs for mapping relationships like social networks, paths, dependencies, or flows (e.g., maps, pipelines).


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

JavaScript — Data Structures (List, Graph, Tree)

Or Copy Link

CONTENTS
Scroll to Top