Loops

While Loop

While Loop General Syntax

while(condition) {
    // do stuff here
}

While Loop Example

i = 0
while(i < 5){
    console.log("Hello")
    i += 1
}
Hello
Hello
Hello
Hello
Hello

For Loop

Example

let sequence = ["The", "Quick", "Brown", "Fox", "Jumps"];
for(let i=0; i<sequence.length; i++) {
    currentItem = sequence[i];
    console.log(currentItem)
}
The
Quick
Brown
Fox
Jumps

Break statement

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;
}
while (sum < goal){
    userInputAsString = prompt("Enter a number: ")
    userInputAsInteger = parseInt(userInputAsString)
    if (userInputAsInteger < 0){
        continue
    }
    sum = sum + n // not executed if n < 0
}

Nested Loops

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