Skip to the content

Graphs

JavaScript · Unit 23: Data structures

A graph doesn't store a row of data: it stores who is connected to whom. Friendships, streets between neighborhoods, bus stops.

The most common shape is an object: each key is a point and its value is the array of its neighbors.

const g = {
  mia: ["leo", "ava"],
  leo: ["mia"],
  ava: ["mia"],
};
console.log(g.mia);
console.log(g.mia.length);

Prints

[ 'leo', 'ava' ]
2

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    What does this code print?

  2. 2. Complete the code

    Fill in the blank to ask whether leo is one of mia's neighbors.

  3. 3. Predict the output

    What does this code print?

  4. 4. Multiple choice

    What is true about this graph?

  5. 5. Put the lines in order

    Put linked(g, a, b) in order. It says whether a connection leaves a towards b, and gives false if a isn't even in the graph.

  6. 6. Predict the output

    This graph has no way back, so the Set isn't needed. In what order does it print?

  7. 7. Complete the code

    Fill in the blank so nobody gets visited twice.

  8. 8. Find the bug

    It should walk breadth-first: a first, then its two neighbors b and c, and d at the very end. Which line has the error?

  9. 9. Find the case that fails

    howMany(p) returns how many neighbors that person has, or 0 if they aren't in the graph. Which call breaks it?

  10. 10. Predict the output

    The walk starts at mia and seen keeps whoever it reached. What does it print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →