Control Flow

What we’ll cover

Block Scope

Conditional Statements

If Statements General Syntax

if(condition){ // this is a check
    statement1
    statement2
}

If Statements Example

if(5 > 10){ // this is a check
    print("5 is greater than 10!")
}

If/Else Statements General Syntax

if (condition){
    statement1
} else {
    statement2
}

If/Else Statements Example

if (condition1){
    statement1
} else if(condition2) {
    statement2
}

If/Else If Statements General Syntax

if (condition){
    statement1
} else if(condition2) {
    statement2
} else {
    statement3
}

Loops

The while loop executes a statement (which may be a block statement) while a condition is true

while(condition){
    statement
}

The while loop will never execute if the condition is false at the outset

If you want to make sure a block is executed at least once, ensure the initial condition is set to True, then internally changed to False to break out of the loop

continueCondition = true
while(continueCondition){
    if(breakCondition){
        continueCondition = False
    }
}

Determinate Loops

The for loop is a general construct to support iteration controlled by a counter or similar variable that is updated after every iteration.

for(let i=0; i<10; i++) {
    console.log(i);
}

Nested Loops

You can have loops within loops, but be aware of variable scoping:

for(let i=0; i<10; i++) {
  console.log(i);
  for(let j=0; j<10; j++) {
      console.log(j);
  }
}

Statements That Break Control Flow

The same break statement that you use to exit a switch can also be used to break out of a loop

paymentPerYear = 10000;
interestRate = 0.05;
currentYear = 0;
balance = 0;
while (currentYear <= 100) {
    balance += paymentPerYear;
    interest = balance * interestRate / 100;
    balance += interest;
    if (balance >= goal) {
        break;
    }
    currentYear += 1;
}

The continue statement transfers control to the header of the innermost enclosing loop

while (sum < goal){
    userInputAsString = prompt("Enter a number: ")
    userInputAsInteger = parseInt(userInputAsString)
    if (userInputAsInteger < 0){
        continue
    }
    sum = sum + n // not executed if n < 0W
}