C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Result: The program begins at 0 and stops at 4. When "i" reaches 5, the loop is terminated before being run again.
JavaScript program that uses for-loop
// Loop over first 5 numbers and print them.
for (var i = 0; i < 5; i++) {
console.log("FOR-LOOP ITERATION: " + i);
}
Output
FOR-LOOP ITERATION: 0
FOR-LOOP ITERATION: 1
FOR-LOOP ITERATION: 2
FOR-LOOP ITERATION: 3
FOR-LOOP ITERATION: 4
So: We usually prefer "for" when the end point is known. But for an infinite loop or one where we do not know here it stops, while is good.
JavaScript program that uses while-loop
// Use while-loop over first five numbers.
var i = 0;
while (i < 5) {
console.log("WHILE INDEX: " + i);
i++;
}
Output
WHILE INDEX: 0
WHILE INDEX: 1
WHILE INDEX: 2
WHILE INDEX: 3
WHILE INDEX: 4
JavaScript program that uses for-of loop
var numbers = [10, 20, 30];
// Loop over the numbers in the array.
for (var number of numbers) {
console.log("FOR OF: " + number);
}
Output
FOR OF: 10
FOR OF: 20
FOR OF: 30
JavaScript program that uses for-in loop
var numbers = [10, 20, 30];
// Loop over the indexes.
// ... The "i" identifier is a standard index variable name.
for (var i in numbers) {
console.log("INDEX: " + i);
console.log("ELEMENT: " + numbers[i]);
}
Output
INDEX: 0
ELEMENT: 10
INDEX: 1
ELEMENT: 20
INDEX: 2
ELEMENT: 30