How to Implement Graph in JavaScript: Simple Guide
To implement a graph in JavaScript, use an
object or Map to store nodes and their edges as adjacency lists. Each key represents a node, and its value is an array of connected nodes, allowing easy addition and traversal.Syntax
A graph can be represented as an adjacency list using a JavaScript object or Map. Each key is a node, and its value is an array of nodes it connects to.
Example parts:
graph[node]: Access edges ofnode.graph[node].push(neighbor): Add an edge fromnodetoneighbor.
javascript
const graph = { A: ['B', 'C'], B: ['A', 'D'], C: ['A'], D: ['B'] };
Example
This example shows how to create a graph, add edges, and print connections for each node.
javascript
class Graph { constructor() { this.adjacencyList = {}; } addVertex(vertex) { if (!this.adjacencyList[vertex]) { this.adjacencyList[vertex] = []; } } addEdge(v1, v2) { if (this.adjacencyList[v1] && this.adjacencyList[v2]) { this.adjacencyList[v1].push(v2); this.adjacencyList[v2].push(v1); // For undirected graph } } printGraph() { for (const vertex in this.adjacencyList) { console.log(vertex + ' -> ' + this.adjacencyList[vertex].join(', ')); } } } const graph = new Graph(); graph.addVertex('A'); graph.addVertex('B'); graph.addVertex('C'); graph.addVertex('D'); graph.addEdge('A', 'B'); graph.addEdge('A', 'C'); graph.addEdge('B', 'D'); graph.printGraph();
Output
A -> B, C
B -> A, D
C -> A
D -> B
Common Pitfalls
Common mistakes include:
- Not initializing nodes before adding edges, causing errors.
- Forgetting to add edges in both directions for undirected graphs.
- Using arrays without checking duplicates, which can cause repeated edges.
javascript
class Graph { constructor() { this.adjacencyList = {}; } // Wrong: addEdge without checking vertices addEdge(v1, v2) { this.adjacencyList[v1].push(v2); // Error if v1 not added this.adjacencyList[v2].push(v1); } // Right: check and add vertices if missing addVertex(vertex) { if (!this.adjacencyList[vertex]) { this.adjacencyList[vertex] = []; } } addEdgeSafe(v1, v2) { this.addVertex(v1); this.addVertex(v2); if (!this.adjacencyList[v1].includes(v2)) { this.adjacencyList[v1].push(v2); } if (!this.adjacencyList[v2].includes(v1)) { this.adjacencyList[v2].push(v1); } } }
Quick Reference
| Operation | Description | Example |
|---|---|---|
| Add Vertex | Create a new node in the graph | graph.addVertex('A') |
| Add Edge | Connect two nodes (undirected) | graph.addEdge('A', 'B') |
| Access Neighbors | Get nodes connected to a node | graph.adjacencyList['A'] |
| Print Graph | Show all nodes and edges | graph.printGraph() |
Key Takeaways
Use an adjacency list with objects or Maps to represent graphs in JavaScript.
Always add vertices before connecting edges to avoid errors.
For undirected graphs, add edges in both directions.
Check for duplicate edges to keep the graph clean.
Use classes to organize graph operations clearly.