Lessons · JavaScript · loop inside a loop
A loop inside a loop multiplies
n items in the outer loop times n in the inner is n squared. 1,000 becomes a million.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Fine on demo data, a frozen tab on real data. Spotting the shape early is the fix.
How to think about it
Is the inner loop searching? If the inner loop is searching, replace it with a Set or Map lookup. If both loops are genuinely needed (a grid), keep the body tiny.
Worked example
const dupes = names.filter((n, i) => names.indexOf(n) !== i);indexOf is a hidden inner loop: n squared.
const seen = new Set(); const dupes2 = [];Instead: one pass with memory.
for (const n of names) { if (seen.has(n)) dupes2.push(n); seen.add(n); }n steps.Your turn
Visit every cell of a 3x3 grid.
for (let r = 0; r < 3; r++) for (let c = 0; c < ; c++) visit(r, c);
Solve one with the tests running
The trap
includes or indexOf inside a loop. Two loops disguised as one.
Practise loop inside a loop on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.