Using While Loop in JavaScript
In the JavaScript while loop, the codes between blocks are executed as long as the condition is true.
Spelling Rule:
while (condition) {
Codes to be run
}
Condition: Execute the loop as long as it is true.
Example 1: Example used to print numbers from 0 to 9.
Description: Before the loop var i=0; The variable is defined and its initial value is assigned. As long as i<10, the loop will be executed. To break the condition within the loop, the value in variable i is increased with i++.
var i=0;
while (i < 10) {
document.write("Number = " + i);
i++;
}
Example 2: Printing array elements to the screen with a while loop.
Explanation: In the first three lines, variables are defined and values are assigned. With while(fruits[i]), as long as the loop value is full, the value true will be produced and the array elements will be entered into the loop and written to the text variable. The i++ value will be incremented by 1 in the loop and a false value will be generated for the undefined value after the last index value in the fruits array.
var fruits = ["Apple", "Pear", "Cherry", "Watermelon"];
var i = 0;
var text = "";
while (fruits[i]) {
text += fruits[i] + "<br>";
i++;
}
document.write(fruits);
Example 3: The most important rule in the loop; The loop should not go into an infinite loop. To do this, a command to exit the loop (break) or a change that will break the condition in the loop must be written.
while (true) {
document.write("hello world");
//ATTENTION: the program will enter an infinite loop and will not terminate.
}
Example 3 correction: A code like the following can be written to remove the program from the infinite loop.
var i=0;
while (true) {
document.write("hello world");
//ATTENTION: the program will enter an infinite loop and will not terminate.
}
if(i>=10)break; //When i reaches 11, the loop will not exit.