Repetition Loop

Statements can be run repeatedly in several ways:while(cyclecondition){statements;}do {statements;} while(cyclecondition);for (pre-loop statements;cycle condition;cycle statements;){statements;}for (propertyinobject){statements;}for (elementofiterable){statements;}

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


RESETRUNFULL
<!DOCTYPE html><html><body><script>

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

</script></body><html>

<!DOCTYPE html><html><body><script>

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

</script></body><html>

<!DOCTYPE html><html><body><script>

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

</script></body><html>

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 [].


RESETRUNFULL
<!DOCTYPE html><html><body><script>

var s="";var obj={firstName:"John",lastName:"Brooks",age:30}for (let x in obj) s+=obj[x];console.log(s); // JohnBrooks30

</script></body><html>

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.


RESETRUNFULL
<!DOCTYPE html><html><body><script>


   arr = [ 3, 5, 7 ];
   arr.foo = "hello";
   for (let i in arr) console.log(i); // 0, 1, 2, foo
   for (let i of arr) console.log (i); // 3, 5, 7

</script></body><html>

(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.


RESETRUNFULL
<!DOCTYPE html><html><body><script>

for (var i=0; i<5; i++){}console.log(i);   // 5, not 4

</script></body><html>

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


RESETRUNFULL
<!DOCTYPE html><html><body><script>

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

</script></body><html>

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


RESETRUNFULL
<!DOCTYPE html><html><body><script>

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

</script></body><html>

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


RESETRUNFULL
<!DOCTYPE html><html><body><script>

var m;outerloop:for (let i=0; i<10; i++){
   for (let 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

</script></body><html>