Creating a Graph in Javascript

We'll be creating a graph class that supports weights and both directed and undirected types. This will be implemented using an adjacency list. As we move to more advanced concepts, both weights and directed nature of the graphs will come in handy.

An adjacency list is an array A of separate lists. Each element of the array Ai is a list, which contains all the vertices that are adjacent to vertex i. We're defining it using 2 members, nodes and edges.

Graph Class Structure

Let's set up the graph class by defining our class and some methods that we'll use to add nodes and edges to our graph.

We'll initially define the following methods:

  • addNode: Adds a node to the graph
  • addEdge: Adds an undirected edge to the graph
  • addDirectedEdge: Adds a directed edge
  • display: Shows the graph structure

Implementation

class Graph {
    constructor() {
        this.edges = {};
        this.nodes = [];
    }
    
    addNode(node) {
        this.nodes.push(node);
        this.edges[node] = [];
    }
    
    addEdge(node1, node2) {
        this.edges[node1].push(node2);
        this.edges[node2].push(node1);
    }
    
    addDirectedEdge(node1, node2) {
        this.edges[node1].push(node2);
    }
    
    display() {
        let graph = "";
        this.nodes.forEach(node => {
            graph += node + "->" + this.edges[node].join(", ") + "<br>";
        });
        console.log(graph);
    }
}

Example Usage

You can test these methods and our class using:

let g = new Graph();
g.addNode("A");
g.addNode("B");
g.addNode("C");
g.addNode("D");
g.addNode("E");

g.addEdge("A", "C");
g.addEdge("A", "B");
g.addDirectedEdge("A", "D");
g.addEdge("D", "E");

g.display();
A->C, B, D
B->A
C->A
D->E
E->D

How It Works

The graph uses an adjacency list representation where:

  • nodes: Array storing all vertices in the graph
  • edges: Object where each key is a node and value is an array of connected nodes
  • addEdge: Creates bidirectional connection (undirected edge)
  • addDirectedEdge: Creates unidirectional connection (directed edge)

Graph Types Comparison

Edge Type Method Connection
Undirected addEdge() Bidirectional (A?B)
Directed addDirectedEdge() Unidirectional (A?B)

Conclusion

This graph implementation provides a foundation for building more complex graph algorithms. The adjacency list approach offers efficient storage and easy traversal for most graph operations.

Updated on: 2026-03-15T23:18:59+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements