0
Challenge · 11Just Enough JavaScript

Nested loops and what they cost

JavaScriptused in ~95% of apps

A loop inside a loop is the most natural thing to write and the most common reason a correct solution runs out of time. You need to be able to spot one and know roughly what it costs, on sight.

Core idea. A loop inside a loop runs the inner body once for every pair of items. Ten items means a hundred passes. A thousand items means a million. The code grows by two lines. The work grows enormously.
Playground, this isn't a screenshot
how fast the work grows
1010
100
100100
10,000
1,0001,000
1,000,000
10,00010,000
100,000,000
one loop. Grows in step with the listloop inside a loop. Grows by multiplication

Ten thousand items is nothing for one loop. For a nested loop it is a hundred million passes.

↑ play a little first, then dig in