reading-notes

Class 8 - Operators and Loops

(Expressions & Operators can be found in the Class-7 notes)

Loops and Iteration


for Statement

A for loop repeats until a specified condition evaluates to false and looks like the following:

for ([initialExpression]; [conditionExpression]; [incrementExpression])
  statement

When a for loop executes, the following occurs:

  1. The initializing expression initialExpression, if any, is executed. This expression usually initializes one or more loop counters, but the syntax allows an expression of any degree of complexity. This expression can also declare variables.
  2. The conditionExpression expression is evaluated. If the value of conditionExpression is true, the loop statements execute. Otherwise, the for loop terminates. (If the conditionExpression expression is omitted entirely, the condition is assumed to be true.)
  3. The statement executes. To execute multiple statements, use a block statement ({ }) to group those statements.
  4. If present, the update expression incrementExpression is executed.
  5. Control returns to Step 2.
function howMany(selectObject) {
  let numberSelected = 0;
  for (let i = 0; i < selectObject.options.length; i++) {
    if (selectObject.options[i].selected) {
      numberSelected++;
    }
  }
  return numberSelected;
}

const btn = document.getElementById('btn');

btn.addEventListener('click', () => {
  const musicTypes = document.selectForm.musicTypes;
  console.log(`You have selected ${howMany(musicTypes)} option(s).`);
});

while Statement

while (condition)
  statement
let n = 0;
let x = 0;
while (n < 3) {
  n++;
  x += n;
}

Example 1

With each iteration, the loop increments n and adds that value to x. Therefore, x and n take on the following values:

After completing the third pass, the condition n < 3 is no longer true, so the loop terminates.

Example 2

Avoid infinite loops. Make sure the condition in a loop eventually becomes false—otherwise, the loop will never terminate! The statements in the following while loop execute forever because the condition never becomes false:

// Infinite loops are bad!
while (true) {
  console.log('Hello, world!');
}