JavaScript: an index turns a scan into a lookup
Without an index, a database finds a row by scanning the table and testing every row, which takes time proportional to the table size. An index is an extra structure that maps a column value to the row, so the same query needs only a lookup.
JavaScript
const users = Array.from({ length: 1000 }, (_, i) => ({ id: i + 1, name: "user" + (i + 1) }));
let scanSteps = 0;
function findByScan(id) {
for (const user of users) {
scanSteps++;
if (user.id === id) return user;
}
return null;
}
const byId = new Map(users.map((user) => [user.id, user]));
console.log(findByScan(900).name + " after " + scanSteps + " rows scanned");
console.log(byId.get(900).name + " after 1 index lookup");
console.log("missing id: " + byId.get(5000) + ", scan finds " + findByScan(5000));