Data Structures Explained
Choose a data structure by comparing arrays, maps, stacks, queues, trees, and graphs.
On this page
Data Structures Explained
A data structure organizes values so your program can perform particular operations efficiently. Start with what the program does most often: reading by position, finding an item by key, processing arrivals in order, or following relationships.
Arrays and maps
Use an array when order matters or when you need to read a value by position. Access by index is typically constant time. In an array-backed list, inserting near the front generally requires shifting the elements that follow.
Use a map when the usual question is “which value belongs to this key?” A hash-based map typically offers constant-time lookup on average under suitable hashing assumptions. A balanced tree map makes a different trade-off: ordered keys with logarithmic lookup.
const readers = ["Lina", "Omar", "Noor"];
const byId = new Map([
["r-42", { name: readers[0] }],
["r-73", { name: readers[1] }],
]);
console.log(readers[1]); // Omar
console.log(byId.get("r-42")); // { name: "Lina" }
console.log(byId.get("r-00")); // undefinedHere the array keeps display order and the map supports lookup by ID. If both represent the same collection in a real application, keep their updates consistent.
Stacks and queues
A stack takes the most recently added item first. Undo history is a common example. A queue takes the oldest waiting item first, as in a line of print jobs. A queue built on an array can maintain an index for the front to avoid shifting all elements on each removal. A long-lived queue must also release or reuse consumed storage.
Trees and graphs
A tree represents a hierarchy. A folder tree, for instance, gives each non-root folder one parent. A graph represents more general relationships. In a course catalog, a course can have multiple prerequisites, and one prerequisite can serve several courses. A traversal should track visited nodes when it might revisit a node.
Choose by operation
For a library, use an array for the ordered reading list, a map for lookup by article ID, and a queue for jobs waiting to build the search index. Use a tree for nested categories or a graph for cross-links between articles. Before choosing, identify your frequent operations and check their cost against Algorithms and Complexity.