Intermediate·Concept·2 min read

Graphs in JavaScript

Practice this question

Graph representation

JavaScript
const graph = {
  A: ['B', 'C'],
  B: ['D'],
  C: ['E'],
};

Problems to practice

  • Number of Islands
  • BFS/DFS traversal
  • Course Schedule
  • Clone Graph
  • Shortest Path in Unweighted Graph
  • Topological Sort

Example: BFS

JavaScript
function bfs(graph, start) {
  const visited = new Set([start]);
  const queue = [start];

  while (queue.length) {
    const node = queue.shift();
    console.log(node);

    for (const neighbor of graph[node] || []) {
      if (!visited.has(neighbor)) {
        visited.add(neighbor);
        queue.push(neighbor);
      }
    }
  }
}

Adapted from 16_DSA_JAVASCRIPT.md · “9. Graphs in JavaScript”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.