Jump to main content
Menu

Additional Loop Options

while Loop

  • The while loop is very similar to a for loop.
  • The key difference is that the number of loops before reaching the while loop's terminating condition is not pre-defined.
  • In other words, the number of loops will vary (the for loop has a set number of loops that can be known beforehand).
  • The while loop syntax is:
    while (test condition) {
      // JavaScript statements to execute in each loop
      // JavaScript statement(s) that impact the test condition (to prevent an infinite loop)
    }
  • As long as the the test condition evaluates to true, the loop continues.
  • As soon as the test condition evaluates to false, the loop stops.
  • Inside the loop you will need to somehow move the test condition closer to being false, such as through incrementing (increasing) or decrementing (decreasing) the value with each loop.
  • Giving the test condition variable a starting value before the loop begins is also recommended, so that the loop starts properly. Just make sure not to pass a value that stops the loop before it starts!

while Loop Example

console.log('HTML Headings from Largest to Smallest');
let size = 1;
while (size < 7) {
  console.log('<h' + size + '>');
  size++;
}

// Developer Tools Console output:
// HTML Headings from Largest to Smallest
// <h1>
// <h2>
// <h3>
// <h4>
// <h5>
// <h6>

do-while Loop

  • This type of loop is a variation on the while loop and moves the test condition to the end of the code, rather than having it at the start.
  • With a do-while loop you are guaranteed to have the code execute at least once, which is not guaranteed in a while loop.
  • The do-while loop syntax is:
    do {
      // JavaScript statements to execute in each loop
      // JavaScript statement(s) that impact the test condition (to prevent an infinite loop)
    }
    while (test condition);
    
  • As long as the the test condition evaluates to true, the loop continues.
  • As soon as the test condition evaluates to false, the loop stops.

do-while Loop Example

console.log('HTML Headings from Largest to Smallest');
let size = 1;
do {
  console.log('<h' + size + '>');
  size++;
}
while (size < 7);

// Developer Tools Console output:
// HTML Headings from Largest to Smallest
// <h1>
// <h2>
// <h3>
// <h4>
// <h5>
// <h6>

continue Statement

  • This statement can be used in for, for-of, for-in, while, and do-while loops.
  • When continue is encountered, the loop skips to the next iteration:
    • In for loops the test condition would increment or decrement.
    • For while and do-while loops the while condition would be checked.
  • The code following continue (the other statements that would have happened in that loop) is skipped.
  • By default continue works on the loop level where it is called; this is important because loops can be nested.
  • You can pinpoint exactly what loop you wish to iterate by specifying a label for the target loop. Labels are a name followed by a colon, such as:
    testLoop: for (let i=0; i<allTestItems; i++) {
      // nested loops code, which include the next line
      continue testLoop;
    }
    
  • In the example, the continue would result in the outer loop skipping to its next iteration.
  • A label can be paired with continue for all the various types of loops.

break Statement

  • This statement can be used in for, for-of, for-in, while, and do-while loops, as well as the switch() control structure.
  • When break is encountered, the loop stops completely.
  • The code following break is skipped; no additional conditions are checked and no further looping occurs.
  • By default break works on the loop level where it is called; this is important because loops can be nested.
  • You can pinpoint exactly what loop you wish to break by specifying a label for the target loop.
  • As with labels for continue, these are a name followed by a colon. An example is:
    testLoop: for (let i=0; i<allTestItems; i++) {
      // nested loops code here
      break testLoop;
    }
    
  • In the example, the outer loop would immediately stop. Nested loops would continue to function until they ran their course.

Pre-Increment / Pre-Decrement

  • Post-incrementing (e.g., i++) is typically used to increment for loops.
  • It is also possible to pre-increment (e.g., ++i).
  • The difference is that i++ increments after that loop's code has run, while ++i increments before that loop's code has run.
  • The same before / after behavior is true of i-- (post-decrement) and --i (pre-decrement)
  • When used outside of a loop, ++i and --i modify the variable's value before the assignment or display occurs, while i++ and i-- change the value after the assignment or display occurs.

for-in Loop

  • These loops are treated differently than the other loops because they are meant for a very specific scenario: looping through the properties of an Object object (such as an object literal).
  • Symbols are omitted from the loop results, because they are private.
  • Objects in JavaScript will inherit properties from other objects (remember there is an Object object at the very top of the prototypal hierarchy), so there is a hasOwnProperty() method on all objects which returns a boolean result if the property passed to the method is actually one of its properties and is not inherited. This is very helpful if you're running this type of loop on anything that is below the Object object.
  • The example shows the inclusion of hasOwnProperty(), although in this case it has no impact on the result.

for-in Loop Example

const sampleObject = {
  a : 'Yes', 
  b : 'No', 
  c : 'Maybe'
};

for (const theProperty in sampleObject) {
  if (sampleObject.hasOwnProperty(theProperty)) {
    console.log(`sampleObject.${theProperty} = ${sampleObject[theProperty]}`);
  }
}

// Developer Tools Console output:
// sampleObject.a = Yes
// sampleObject.b = No
// sampleObject.c = Maybe