Basics
Algorithm speed: Big O
Not "how many seconds" but "how many times slower when there's more data".
Why it exists
On 10 items any code is fast. Trouble starts with real data: 100,000 products, a million log entries. An algorithm with a nested loop, unnoticeable in tests, takes minutes on them. Big O lets you estimate that before running — from how the code is built, not with a stopwatch. It's the main language for discussing code in interviews.
Where it's used
Syntax
O(1) — index access, Map.has
O(log n) — binary search
O(n) — one pass over an array
O(n log n) — sorting
O(n²) — a nested loop over the same dataExamples
const n = 1000;
const pairs = (n * (n - 1)) / 2;
pairs; // → 499500const n = 1_000_000;
Math.ceil(Math.log2(n)); // → 20const ids = Array.from({ length: 5 }, (_, i) => i);
const set = new Set(ids);
ids.includes(4); // → true
set.has(4); // → trueincludes scans the array and has doesn'tconst n = 10_000;
const nested = n * n;
const withMap = n;
nested / withMap; // → 10000Results after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
Big O answers: if there's 10 times more data, how many times more work is there? Constants and details are dropped — only the shape of the growth matters.
- O(1) — constant:
arr[i],map.get(key),set.has(x). Independent of size. - O(log n) — each step discards half: binary search. A million elements take 20 steps.
- O(n) — one pass: for...of, map, filter, includes,
indexOf. - O(n log n) — a good sort (sort).
- O(n²) — another pass for each element: nested loops, includes or
indexOfinside a loop.
For n = 1,000,000: O(log n) ≈ 20 operations, O(n) a million, O(n²) a trillion (hours of work).
Hidden loops count too: arr.includes(x) inside a for is O(n²), even though only one loop is written.
Traps
How it differs from…
sort()andtoSorted()Sorting costs O(n log n): don't sort for a single maximum — that's O(n) in one pass.
When to pick something else
Don't sacrifice readability for complexity on small, fixed data (a 7-item menu, the days of the week). Big O is a tool for growing data, not a reason to complicate every loop.