In this video, you gave every game on your shelf an id and wrote a function that finds a game by its id instead of by its position.
Key Points
- A record’s position belongs to the list and can shift when the list changes. An id is a field that stays with the record, like a sticker on a game box. Each game gets its own id, so one id points to one game.
console.table()shows both side by side. The(index)column is each record’s position, and theidcolumn is its id. Catan sits at position2, but its id is7.- To find a record by its id, loop over the list and compare each record’s
idfield with the id you want. When they match, return that record right away, which also stops the loop. If no record matches, the loop runs to the end and the function returnsundefined. If an id were ever repeated, the search would return the first record with it, which is why each id belongs to one record only. - A number in square brackets after the list is a position, while an id is a field you compare. That’s why
games[2]gives you Catan, butfindGame(games, 2)gives you Azul, whose id is2. - The search returns the list’s own record, not a copy. When you change a field of the found record, the change shows up in the list too.
The Final Code
scratch/shelf.js
const games = [
{ id: 12, title: "Ticket to Ride", maxPlayers: 5, minutes: 60 },
{ id: 3, title: "Codenames", maxPlayers: 8, minutes: 15 },
{ id: 7, title: "Catan", maxPlayers: 4, minutes: 90 },
{ id: 2, title: "Azul", maxPlayers: 4, minutes: 45 },
];
function findGame(games, id) {
for (const game of games) {
if (game.id === id) {
return game;
}
}
return undefined;
}
console.log(games[2].title);
console.log(findGame(games, 2).title);
const found = findGame(games, 7);
found.minutes = 120;
console.table(games);