To execute a set of statements when a condition is true, use the while loop.
The following code demonstrates how to use the while loop.
var number = 1;
var sum = 0;
while (number < 11) {
sum += number;
++number;
console.log(number);
}
console.log(sum);
To execute a set of statements a specified number of times, use the for loop.
The following code shows how to sum integers using a for loop
var number = 1;
var sum = 0;
for (var number = 1; number < 11; number++) {
sum += number;
console.log(sum);
}
console.log(sum);
for loops are used frequently to access the elements of an array, as shown in the following example.
var numbers = [31, 17, 12, 22, 100, 1, 2, 3, 4, 4, 5, 65, 6, 7, 78,999];
var sum = 0;
for (var i = 0; i < numbers.length; ++i) {
sum += numbers[i];
console.log(sum);
}
console.log(sum);