You are building a cashier app for a fruit shop. A customer asks, "Any oranges left?" If the list of fruit is stored in a row, the program has to check the items one by one until it finds the orange. If each fruit's name is stored as a pair with its stock, the program asks for "orange" and gets the answer right away. With four fruits you won't notice the difference. With a million items you will.
A data structure is a way of storing and arranging data, so that the data is easy and quick to read, add or remove. The two ways of storing above are two different data structures. You already know two data structures: arrays and objects. Things at home are stored in different ways too: books stand in a row on a shelf, plates sit in a stack, and socks go in a labelled drawer. The reason is that you take each of them out in a different way. The same goes for data: you choose how to store it by how you will read it.
Same data, two ways to store it
The code below stores the fruit shop's data in two ways: the array fruits and the Map stock.
// Array: in a row, read by position number
const fruits = ["Apple", "Banana", "Orange", "Grape"];
console.log(fruits[1]); // Banana
// Map: key and value pairs, read by name
const stock = new Map([
["apple", 5],
["banana", 12],
["orange", 8],
]);
console.log(stock.get("apple")); // 5
fruitsis an array. Its items sit in a row, and each item has a position number called its index. Indexes start at 0, so"Apple"is at index 0 and"Banana"is at index 1.- With
fruits[1], the computer jumps directly to index 1 without passing"Apple". The third fruit is atfruits[2], and the computer jumps directly there too. stockis a Map, a structure that stores key and value pairs, much like an object. Each line insidestockis one pair of a fruit's name (the key) and its stock (the value): the key"apple"has the value5.stock.get("apple")reads a value by its key. You don't need to know the position of the pair, only its key.
An array and a Map both store data, but you read the data in different ways. An array fits when you often read items by position. A Map fits when you often look things up by name.
Why the choice matters
Say you want to know whether there is an orange. In an array, you don't know which index holds the orange. So the simplest way is to check the items one by one from the front. In a Map, you only give the key. This table compares the steps in the array and in the Map:
| Step | Array fruits: find "Orange" |
Map stock: get("orange") |
|---|---|---|
| 1 | check "Apple": no |
straight to the key "orange": 8 |
| 2 | check "Banana": no |
already done |
| 3 | check "Orange": found |
With four items, the difference is only two steps. With a million items, the array may need a million checks, while the Map usually still finds the key right away. So a data structure decides two things. First, how many steps each operation needs, for example searching or adding. More steps take more time. Second, how much memory it uses. Memory is where the computer keeps data while a program runs. A Map is quick at looking things up, but it uses more memory than an array that holds the same data.
The data structures you'll learn
| Structure | Picture it as | Good for |
|---|---|---|
| Array | books in a row on a shelf | reading by position |
| Stack | a stack of plates: the last one put on is the first taken off | undo, the Back button |
| Queue | a line: whoever comes first is served first | task queues |
| Linked list | a chain: each item points to the next one | adding and removing at the front |
| Hash map | a labelled drawer | looking up by name |
| Tree | folders inside folders | data with levels |
| Graph | a map: cities and roads | networks, routes, friendships |
Arrays, stacks, queues and linked lists are called linear structures: their items stand in a line, one behind the other. Trees and graphs are called non-linear: one item can be connected to many other items. A hash map, such as the Map stock above, is read by key, not by position.
⚠️ Three ways to pick the wrong data structure
- Picking whatever looks clever. If you only add and take items at one end, a plain array is enough. A tree used for no reason only makes the code harder to read.
- Judging from small data. With ten items, every structure feels fast. The difference only shows with thousands or millions of items.
- Memorising names. No structure is the best at everything. Each structure is fast at one thing and slow at another. So what you need to understand is the strengths and weaknesses of each structure (the trade-off), not only its name.
🎯 How to choose
Before you choose, ask these four questions:
- Which operation happens most? Reading by position, looking up by name, adding, or removing.
- Does order matter? A queue (a line of people) must keep the order of arrival. A hash map (a labelled drawer) does not need an order.
- Are duplicates allowed? An array can hold the same item twice. Later you'll meet Set, a structure that refuses duplicates.
- How much data is there? A hundred items and a million items may need different choices.
TL;DR: A data structure is a way of storing and arranging data so it's quick to read, add or remove. An array keeps items in a row, and you read each item by its index (the position number, starting at 0). fruits[1] reads the second item of the array fruits directly, without passing the other items. A Map keeps key and value pairs, and you read a value by its key: stock.get("apple") reads the stock of apples. The structure you choose decides how many steps and how much memory each operation, such as a search, uses. The difference grows as the data grows. Arrays, stacks, queues and linked lists are linear structures (their items stand in a line). Trees and graphs are non-linear (one item can be connected to many other items).
⚡ Array: read by position
Write:
const fruits = ["Apple", "Banana", "Orange", "Grape"];
console.log(fruits[1]); // Banana
Guess first: why is fruits[1] Banana and not Apple?
Because the position numbers in an array, called indexes, start at 0. "Apple" is at index 0, so "Banana" is at index 1.
Meaning: An array keeps its items in a row. With fruits[1], the computer jumps directly to index 1 without passing the other items.
⚡ Map: read by name
Write:
const stock = new Map([
["apple", 5],
["banana", 12],
["orange", 8],
]);
console.log(stock.get("apple")); // 5
Meaning: A Map keeps key and value pairs. In stock, the key is the fruit's name and the value is the amount in stock. stock.get("apple") reads a value by its key, so you don't need to know the position of the pair.
⚡ The structure decides time and memory
Guess first: you look for an orange among a million items. Which is faster, the array or the Map?
The Map. In an array, the program doesn't know which index holds the orange, so it checks the items one by one: it may need a million checks. In a Map, the program usually finds the orange right away by its key.
Meaning: A data structure decides how many steps (time) each operation needs, for example a search, and how much memory it uses. A Map is quick at looking things up, but it uses more memory than an array that holds the same data.
⚡ Linear or non-linear
Meaning: Linear structures keep their items in a line, one behind the other: arrays, stacks (piles), queues (lines of people) and linked lists (chains). In non-linear structures, one item can be connected to many other items: trees (levels, like folders inside folders) and graphs (networks, like cities and roads on a map). A hash map, such as a Map, is read by key, not by position.