JavaScript while Loop
JavaScript while Loop check condition and execute while block for a specify number of times, until while condition become false.
In JavaScript while loop check first condition. If condition become true then execute block of code.
Syntax
while (condition) {
statements; // Do stuff if while true
increment; // Update condition variable value
}
while (true) { // condition evaluates to true
...
...
}
while (1) { // Condition always true
...
...
}
Example: Following while loop example execute block of code until number
value become 10
. When number
value become 11
the condition no longer satisfy and finally skip to execute while block.
<script>
number = 1;
while (number <= 10) {
document.writeln(number + " times");
number++;
}
document.writeln("Total " + (number - 1) + " times loop repeat");
</script>
Example Result
Array Loop (JavaScript while loop)
While loop to go through array,
JavaScript array.length
property indicates length of a array.
<script>
var arr = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100];
number = 0;
while (number < arr.length) {
document.writeln("Value of arr[" + number + "] : " + arr[number]);
number++;
}
document.writeln("End of Loop.");
</script>
Example Result
Reverse Array Loop (JavaScript while Loop)
Following example display all array elements value in reverse order.
<script>
var arr = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100];
number = arr.length;
while (number--) {
document.writeln("Value of arr[" + number + "] : " + arr[number]);
}
document.writeln("End of Loop.");
</script>
Example Result