Repetition Loop

Statements can be run repeatedly in several ways:
while(cycle condition){statements;}
do {statements;} while(cycle condition);

for (pre-loop statements; cycle condition; cycle statements;){statements;}
for (property in object){statements;}
for (element of iterable){statements;}

Each of these code segments calculates the sum of 0 to 9.


let i = 0, sum = 0;

while (i < 10) {
  sum += i;
  i++;
}

let i = 0, sum = 0;

do {
  sum += i++;
} while (i < 10);

for (let i = 0, sum = 0; i < 10; i++) sum += i;

for...in loops through the properties of an object or elements of an array. Notice here that x is a string that contains the property name. Think of it as referencing the variable in [].


var s = "";
var obj = {firstName: "John", lastName: "Brooks", age: 30};

for (let x in obj) s += obj[x];

console.log(s);

JohnBrooks30

Think of for...of loops as iterating through the values of the iterable. for...of loops are, in a way, more limiting than for...in loops, as for...of loops work with only objects that are iterables. The following illustrates some differences between for...in and for...of.


arr = [3, 5, 7];
arr.foo = "hello";

for (let i in arr) console.log(i);

for (let i of arr) console.log(i);

0 1 2 foo 3 5 7

(If you wish to us e for-of loops to iterate over an object which is not an iterable , consider using a Map instead of the object, as a Map is an iterable.)

After the last cycle, the 'cycle statement' is executed, before the loop finally ends.


for (var i = 0; i < 5; i++) {}

console.log(i);

5

break; gets the execution out of the current-level loop instantly.


for (var i = 0; i < 10; i++) {
  if (i > 3) break;
  console.log(i);
}

console.log(i);

0 1 2 3 4

continue; ends the current-levelloop cycle and continues with the next cycle.


for (var i = 0; i < 10; i++) {
  if (i > 3) continue;
  console.log(i);
}

console.log(i);

0 1 2 3 10

If used with a label, these two keywords also allow outer loops to be controlled at once.


var m;

outerloop: for (var i = 0; i < 10; i++) {
  for (var j = 0; j < 10; j++) {
    m = i * j;
    if (j > 8) continue;
    if (m > 50) break outerloop;
  }
}

console.log(i + "*" + j + "=" + m);

7*8=56