Representing Graphs with Adjacency List

One of the most common and efficient ways to represent graphs is through an adjacency list.

What is an Adjacency List?

An adjacency list is a way to represent graph data structures where each vertex (or node) stores a list of vertices it is connected to. It's often implemented as a dictionary or a Map in JavaScript, where each key represents a vertex, and its value is an array of connected vertices. Thinking back to the concept of neighbors, we'll store each node's outgoing neighbors in its value array.

Why use an Adjacency List?

  • Efficient Storage: Adjacency lists are particularly efficient for storing sparse graphs, where most vertices have relatively few connections. This means you only need to store the connections that actually exist, saving memory compared to methods that track all possible connections, even those that aren't present.
  • Quick Lookups: You can easily find all connections of a specific vertex by accessing its key.
  • Easy Implementation: Adjacency lists are relatively straightforward to code up.

Adjacency List in JavaScript

We can use a Map or an object to create our adjacency list in JavaScript. Just note that if we decide to use an object, the keys would have to be strings. Since we are working with integers, a Map is a better choice.

const adjList = new Map();
adjList.set(1, [2, 3]);
adjList.set(2, [4]);
adjList.set(3, [5]);
adjList.set(4, []);
adjList.set(5, [6]);
adjList.set(6, []);

Note that graphs can also be represented as an adjacency matrix, which is beyond the scope of this book.

Hi! I'm LSBot. I'm here to help you understand this chapter content with fast , focused answers. Any code from the editor will be automatically included with your question.

Ask me about concepts, examples, or anything you'd like clarified from this chapter. I can explain complex topics, provide examples, or help connect ideas.

Switch to Deep Dive mode if you want comprehensive answers across the entire curriculum. Responses may take longer, but I'll draw on the entire Launch School curriculum to give you a fuller picture.

Want to know more? Refer to the LSBot User Guide .

GitHub Repository Submission

When using GitHub mode, paste your repository URL below and click Save URL to store it. The saved URL will be automatically included with every message you send until you choose to clear it. Learn more

Your GitHub repository URL is saved. LSBot will automatically fetch your latest code from this repository for each message. To change the URL, clear it first and save a new one.
Output
No output yet. Click "Run Code" to execute your code.