Model Any Network of Relationships with Vertices and Edges
Introduction to Graphs
Learn the fundamental vocabulary of graphs — vertices, edges, directed vs undirected, weighted, cyclic vs acyclic, and dense vs sparse — the building blocks for every graph algorithm.
What you'll learn
- Define graphs and distinguish directed from undirected graphs
- Identify weighted, cyclic, acyclic, dense, and sparse graphs
- Recognize real-world problems that map naturally onto graph structures
A graph is a collection of vertices (nodes) connected by edges. Unlike arrays or trees, graphs place no constraints on how nodes connect — any vertex can link to any other, making graphs the right tool for networks, maps, dependencies, and social relationships.
Vertices and Edges
A graph G is written G = (V, E) where V is the set of vertices and E
is the set of edges. An edge connects two vertices. In JavaScript we usually
represent a small example graph like this:
// 4 vertices: 0, 1, 2, 3
// Edges: 0-1, 0-2, 1-3, 2-3
const edges = [
[0, 1],
[0, 2],
[1, 3],
[2, 3],
]; Directed vs Undirected
In an undirected graph an edge between A and B means you can travel in
either direction. In a directed graph (digraph) an edge A → B only lets
you travel from A to B.
Real examples: a road network (undirected), Twitter follows (directed).
Weighted Graphs
A weighted graph assigns a numeric cost to each edge — distance, time, or capacity. Shortest-path algorithms like Dijkstra rely on these weights.
// Weighted edge list
const edges = [
{ from: 0, to: 1, weight: 4 },
{ from: 0, to: 2, weight: 1 },
{ from: 2, to: 1, weight: 2 },
]; Cyclic vs Acyclic
A graph is cyclic if there exists a path from some vertex back to itself. A graph with no such path is acyclic. A directed acyclic graph (DAG) is the backbone of topological sorting, build systems, and dependency resolution.
Dense vs Sparse
The number of edges relative to vertices determines density:
| Term | Edge count | Typical representation |
|---|---|---|
| Sparse | Close to V | Adjacency list |
| Dense | Close to V² | Adjacency matrix |
Most real-world graphs (social networks, road maps) are sparse, which is why adjacency lists are the default choice in JavaScript.
Up Next
Now that you know the vocabulary, learn how to store a graph in memory and compare the tradeoffs of each representation.
Graph Representations →