JavaScript While Loop
The While Loop
The
while
loop loops through a block of code as long as a specified condition
is true.
Syntax
while
(condition)
{
//
code block to be executed
}
<!DOCTYPE html>
<html>
<p id="demo">JavaScript While Loop</p>
<script>
var txt = "";
var i=0;
while (i < 10) {
text += "The number is " + i;
i++;
}
document.getElementById("demo").innerHTML = text;
</script>
</body></html>
The Do/While Loop
The
do/while
loop is a variant of the while loop. This loop will execute the code
block once, before checking if the condition is true, then it will
repeat the loop as long as the condition is true.
Syntax
do
{
//
code block to be executed
}
while
(condition);
<!DOCTYPE html>
<html>
<p id="demo">JavaScript Do/While Loop</p>
<script>
var txt = "";
var i=0;
do {
text += "The number is " + i;
i++;
}
while (i < 10);
document.getElementById("demo").innerHTML = text;
</script>
</body></html>
Comparing For and While
If you have read the previous chapter, about the for loop, you will discover that a while loop is much the same as a for loop, with statement 1 and statement 3 omitted.
Comparing For
<!DOCTYPE html>
<html>
<p id="demo">Comparing For </p>
<script>
var
cars = ["BMW", "Volvo", "Saab", "Ford"];
var i = 0;
var text = "";
for (;cars[i];) {
text += cars[i] + "<br>";
i++;
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
Comparing While
<!DOCTYPE html>
<html>
<p id="demo">Comparing While</p>
<script>
var
cars = ["BMW", "Volvo", "Saab", "Ford"];
var i = 0;
var text = "";
while (cars[i]) {
text += cars[i] + "<br>";
i++;
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
Comments
Post a Comment