Summary of “Loops”. Part 2
While loop
Syntax
while (condition) {
actions
}
Actions will be executed again and again until the condition returns false
.
Accumulation of values in a loop
var sum = 0;
var i = 0;
while (i <= 5) {
sum += 1;
i++;
console.log(i);
}
The program will log:
LOG: 1 (number)
LOG: 2 (number)
LOG: 3 (number)
LOG: 4 (number)
LOG: 5 (number)
LOG: 6 (number) // Loop body code will not be executed, the condition will return false
Calculating percentage of a number
The easiest way to find a percentage of the number is to divide the number by 100 and multiply by the percentage.
// Let’s calculate 2 percent of 100
1000 / 100 * 2 = 20;
// Let’s calculate 7 percent of 1200
1200 / 100 * 7 = 84;
Continue