Programming fundamentals
Data Structures Every Developer Should Know, in Practice
A data structure is a way of arranging data so that the operations you need most, such as lookup, insert or ordering, are cheap. Learning the seven or eight common ones, and what each does well, lets you choose the right container before you write the code instead of fixing a slow one afterwards.
By CodingMarble · Published · 5 min read

Why the container matters as much as the code
Two programs can store the same customer records and behave very differently, because one keeps them in a plain list and the other in a keyed table. The first needs to walk the list to find one customer. The second jumps straight to it. Choosing a data structure means choosing which operations are cheap and which are expensive, and no structure is cheap at everything.
The costs below use Big O terms: O(1) means the work does not depend on size, O(n) means it grows with the number of items, and O(log n) grows very slowly. If those terms are new, the guide on Big O notation explains them first. The figures are the usual ones for the typical implementations in JavaScript, but check the documentation of the runtime or library you use, since details differ.
Arrays: the default for ordered data
An array keeps items in order and lets you reach any item by position. Reading items[5] is O(1). Adding or removing at the end with push and pop is cheap. Inserting or removing at the front or middle is O(n), because the items after the change have to shift. Searching for a value without knowing its position is O(n), since you may have to look at every element.
Arrays are the right default whenever order matters and the collection is read far more than it is searched: a list of products to display, rows returned from a query, the steps in a form. Reach for something else only when a specific operation, usually searching by key or removing from the front, becomes the bottleneck.
Hash maps and Sets: fast lookup by key
A hash map stores key and value pairs and finds a value from its key in O(1) on average. It does this by turning the key into a number that points to a storage slot. In JavaScript you can use a plain object or, more safely for arbitrary keys, a Map. A Set is the same idea with keys only: it answers the question have I seen this before, in about constant time, and it automatically ignores duplicates.
const orders = [
{ id: "A1", customer: "Meera", total: 1200 },
{ id: "B7", customer: "Arjun", total: 540 },
{ id: "C3", customer: "Meera", total: 90 },
];
// Build a Map once: O(n)
const byId = new Map(orders.map((o) => [o.id, o]));
console.log(byId.get("B7").customer); // "Arjun", O(1) on average
// Group with an object of arrays
const byCustomer = {};
for (const o of orders) {
(byCustomer[o.customer] ??= []).push(o);
}
console.log(byCustomer.Meera.length); // 2
// Deduplicate with a Set
const customers = new Set(orders.map((o) => o.customer));
console.log(customers.size); // 2The cost of a hash map is memory and the loss of natural order: a Map remembers insertion order in JavaScript, but it cannot answer give me everything between two keys the way a sorted structure can. Hashing is also only constant on average, and a poor hash function or a flood of colliding keys can degrade it, which is rarely a concern for ordinary application data.
Stacks and queues: control the order of work
A stack is last in, first out: you only add and remove at one end, like a pile of plates. Undo history is the classic case. Every action is pushed, and undo pops the most recent one. The browser call stack that tracks function calls is another, and so is checking whether brackets in an expression are balanced. A queue is first in, first out: items leave in the order they arrived. A job queue for sending emails, a print queue and a request buffer all work this way, and so does breadth-first search in graphs.
// Stack: push and pop at the same end. Both O(1).
const undo = [];
undo.push("type A");
undo.push("type B");
console.log(undo.pop()); // "type B" is undone first
// Queue: add at the back, remove from the front.
class Queue {
constructor() { this.items = {}; this.head = 0; this.tail = 0; }
enqueue(x) { this.items[this.tail++] = x; }
dequeue() {
if (this.head === this.tail) return undefined;
const x = this.items[this.head];
delete this.items[this.head++];
return x;
}
}
const jobs = new Queue();
jobs.enqueue("email-1");
jobs.enqueue("email-2");
console.log(jobs.dequeue()); // "email-1"Notice that the queue avoids array.shift(). On a large array, shift is O(n) in principle because everything moves down one place, although engines optimise it in places. Tracking head and tail indexes keeps both ends cheap whatever the engine does. In production you would usually use a message broker or a library rather than writing your own queue, but the behaviour you rely on is exactly this.
Linked lists: cheap insertion, slow access
A linked list stores each item together with a pointer to the next one. If you already hold a reference to a node, inserting or removing next to it is O(1), because only a couple of pointers change and nothing shifts. The price is that reaching the tenth item means following nine pointers, so access by position is O(n), and the scattered memory layout is unfriendly to the processor cache. Real software uses linked structures inside other things: the internals of some queue and cache implementations, the chain of handlers in middleware, the history of a text editor. In everyday application code an array is nearly always the better choice, and interviews ask about linked lists mostly because they teach pointer thinking.
Trees and graphs: data with relationships
A tree is data with a parent and children and no loops. The HTML DOM is a tree. So are folders on disk, a nested comment thread and a menu with submenus. A binary search tree keeps values ordered so that finding one takes O(log n) when the tree stays balanced, and databases use closely related balanced tree structures to build indexes. Walking a tree is naturally recursive: process a node, then process each child.
const menu = { label: "Home", children: [
{ label: "Services", children: [{ label: "Web", children: [] }] },
{ label: "Contact", children: [] },
] };
function labels(node, depth = 0) {
const own = ["-".repeat(depth) + node.label];
return own.concat(...node.children.map((c) => labels(c, depth + 1)));
}
console.log(labels(menu).join("\n"));
// A graph as an adjacency list: cities and direct routes.
const routes = { Pune: ["Mumbai", "Nashik"], Mumbai: ["Pune", "Surat"],
Nashik: ["Pune"], Surat: ["Mumbai"] };
function reachable(start) {
const seen = new Set([start]);
const queue = [start];
while (queue.length) {
const city = queue.shift();
for (const next of routes[city] ?? []) {
if (!seen.has(next)) { seen.add(next); queue.push(next); }
}
}
return [...seen];
}
console.log(reachable("Surat"));A graph relaxes the rules: nodes connect to any other nodes, and loops are allowed. Road maps, social connections, package dependencies and the links between web pages are graphs. The seen Set in the code matters. Without it, a loop in the graph makes the search run forever, which is the usual bug when people first write graph code.
How to choose
Start from the operation, not the structure. If you mostly iterate in order, use an array. If you look things up by an identifier, build a Map. If you only need to know whether something exists or want to remove duplicates, use a Set. If the order of removal matters, use a stack for newest first and a queue for oldest first. If your data nests, it is a tree. If items connect in arbitrary ways, it is a graph.
Practical tip: before picking a structure, write down the three operations your code will do most often and how often each runs. If lookups by id appear in a loop, that is your signal to index the list into a Map once. Confirm the improvement by timing the code before and after with realistic data sizes.
Finally, resist exotic structures until you have a measured problem. A well-named array and a Map solve the large majority of application needs, and standard library collections are better tested than anything you write in an afternoon.
Keep reading
- Programming fundamentalsBig O Notation Explained Simply, With JavaScript ExamplesBig O notation describes how the work a piece of code does grows as its input grows, not how many seconds it takes on one machine. Once you can count how many times a loop touches the data, you can tell at a glance whether code will stay fast when the input gets a hundred times bigger.
- Programming fundamentalsDatabase Indexing Explained: When It Helps and When It HurtsA database index is a separate, sorted structure that lets the engine jump to matching rows instead of reading the whole table, at the cost of extra storage and slower writes. It only helps when your queries can actually use it, so the habit to build is checking the query plan with EXPLAIN rather than adding indexes on a hunch.
- Programming fundamentalsCaching Explained for Web Developers: Layers and HeadersCaching stores a copy of an expensive result close to whoever needs it next, so repeat requests skip the slow work. The hard parts are deciding how long a copy stays valid and removing it when the original changes, so cache only what is read often, changes rarely and is safe to share.
- Interview questions and cheat sheetsJavaScript Interview Questions and AnswersThis page gives you eighteen JavaScript interview questions, grouped from fundamentals to trick questions, each with a precise answer you can say aloud in under a minute. Code examples are short enough to rewrite on a whiteboard.
Need this built properly for your business?
CodingMarble is a remote studio in India that builds websites, apps and games on fixed packages with the scope written down before payment. Try the free tools we run, or start a project when you are ready.
- On CodingMarble
- Custom software development
- Node.js development
- All guides