JS enginetotaliChecki <= 3truefalse1let total = 0;2for (let i = 1; i <= 3; i++) {3 total = total + i;4}5console.log(total);Console6sum.js:50112341233646
Back: the JavaScript engine, the memory boxes total and i, and the check panelFront: the script sum.js with its loop-back track, and the developer consoleTokens: instructions, the values carried to memory and to the check, and the loop markerAt the back, the JavaScript engine, the two memory boxes total and i, and the check panel. In front, the script as a card with its loop-back track, and the console. The start runs once (i = 1). Before every round the check works out i <= 3; while it is true the body adds i to total, i++ runs, and the loop jumps back to the check. When 4 <= 3 is false the loop ends and console.log prints 6. The order of a for loop is: the start once; then the check; if true, the body and then the update; then the check again. MDN and the ECMAScript specification (ForBodyEvaluation) describe the same order.

Why loops

  1. A loop runs the same lines again and again, so you do not have to copy them. This for loop adds 1, 2 and 3 to a total. Each pass through a loop is called a round, or an iteration.

Before the loop

Round one

More rounds

Leaving the loop

What happens

// step 1/10 · repeat
loop       runs the same lines again and again
round      one pass through the body
           (also called an iteration)
this one   adds 1, 2 and 3 to total
kinds      for, while, do...while, for...of

The order of a for loop is: the start once; then the check; if true, the body and then the update; then the check again. MDN and the ECMAScript specification (ForBodyEvaluation) describe the same order. Because i is made with let in the for line, it only exists inside the loop. JavaScript even makes a fresh copy of i for every round (CreatePerIterationEnvironment in the specification), so code saved in one round keeps that round's i. The figure shows one box.