- Compare frequent operations
- Choose by access and update patterns
- Understand stacks, queues, and maps
Ask the right question
Do not ask which structure is best. Ask which operation you need most often: index access, key lookup, tail insertion, or arrival order.
- Array: order and index access.
- Set: unique values.
- Map: key lookup.
- Stack: last in, first out.
- Queue: first in, first out.
A cart and an index
A cart can be an array because order matters. An id index can be a Map because finding without scanning matters.
const productsById = new Map(
products.map((product) => [product.id, product])
);
productsById.get('prod-42');Every choice has a cost
Two structures can speed up reads but must stay synchronized on writes. Measure the dominant operation before adding indexes.
Choose the structure
Design browser navigation history and a printer job queue.
Show a hint
History returns to the latest state; printers respect arrival order.