Bootcamp Notes – Day 15 (Wed) – Making Loops with JavaScript

 

Making Loops

 

More Operators 

There are some operators that are commonly used in loops because they help to increase or decrease the numeric value of a counter. Let’s take a look at the four most common…

  1. Addition assignment operator +=
  2. Subtraction assignment operator -=
  3. Increment operator ++
  4. Decrement operator

Addition & subtraction assignment operators are binary

Increment & decrement operators are unary – add or subtract 1 from their operand variable.

Increment & decrement can be prefix: ++variable or postfix: variable++

 

While Loops

Loops are a way to repeat a block of code. Their are several ways to create loops in JavaScript but for now we will focus on While Loops.

While loops evaluate a condition that you set. As long as the condition evaluates as true, it will continue to loop. At every iteration, the condition will be re-evaluated.

while (condition to be evaluated) {

… code to run while the condition evaluates as true …

}

Something must happen inside the while loop to cause the condition to be evaluated as false. Otherwise, there would be no way to exit the loop.

While loop example:

let i = 0;

while (i < 5) {

    i += 1;

    console.log(‘This is iteration #’ + i);

}

 

Do.. While Loop Syntax

do {

    …..code to first run once, then loop while the condition evaluates true…

} while (condition to be evaluated);

With the while loop, the condition is evaluated first, so if the condition is false in the beginning, the code inside the block never executes.

With the do… while loop, the loop block executes once before evaluation the condition – so even if the condition is false, the code inside the block will always execute at least once.

 

Do while loop example 1:

do {

    i += 1;

    console.log(‘This is iteration #’ + i);

} while (i  <  5);

Do while loop example 2:

let answer = ‘ ‘;

do {

    answer = prompt(‘Do you like chocolate?’);

} while (answer !== ‘yes’);

 

Additional Resources: