liveBook · Manning

Loop

As explained in Grokking Simplicity

An iteration construct that repeatedly executes a block while progressing through a sequence or range of values.

A for loop repeatedly runs a block while advancing through an array or range. Its logic can often be expressed more clearly with functional tools. section 13.6 section 19.9

Refactor an existing loop by following its data flow:

  • Read the loop and restate its behavior as a series of steps. section 13.6
  • Use clues: one output per input suggests map(), while combining values suggests reduce(). section 13.6
  • Make a subarray, operate on the whole array, and take small steps; reuse average() where appropriate. section 13.8
var answer = []; #1
 
var window = 5;
 
for(var i = 0; i < array.length; i++) { #2
    var sum = 0;
    var count = 0;
    for(var w = 0; w < window; w++) { #3
        var idx = i + w; #4
        if(idx < array.length) {
            sum  += array[idx];
            count += 1; #5
        }
    }
    answer.push(sum/count); #6
}

A nested-loop listing calculates moving averages, exposing the indexing, accumulation, and output steps that can be refactored. section 13.6

How Grokking Simplicity covers it

How deep it goes
Explains loop-to-tool refactoring through behavioral reconstruction and code clues, without examining loop internals.
Examples
Uses nested loops, array slicing, accumulation, and moving averages as refactoring examples.
What you can do after
Apply functional tools to replace existing for loops incrementally.
How it connects
Connects for loops with actions, calculations, data, map(), filter(), reduce(), and forEach().

Also explained in

Compare how 27 books explain loop →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Grokking Simplicity. The section links point to the parts of the book it draws on.