๐Ÿงฎ JavaScript Data Structures & Algorithms
Estimated reading: 5 minutes 108 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 :
Share

JavaScript โ€” Data Structures (List, Graph, Tree)

Or Copy Link

CONTENTS
Scroll to Top