JavaScript While loop
When writing a program, there are times when you need to perform an action over and over. And you have to write a long code to perform those actions. The simplest and easiest way to do is is to write loops.
You can replace those long code with a loop.
While loop
The while loop statement executes a block of code repeatedly for as long as the condition is true. And stops execution once the condition evaluates to
false. The while loop statement test the condition before the expression is executed and once the expression does not comfom with the condition, the loop will never be executed.
Syntax
while (condition) {
statement;
}
Example
<html>
<head>
<title>While loop</title>
</head>
<body>
<script>
var x = prompt ("Enter value");
while(x <10){
document.write(x);
x++;
}
</script>
</body>
</html>
Do..while loop
The do...while loop is similar to while loop but the only difference is that the statement is executed before the condition is checked. The condition is evaluated at the end.
Syntax
do {
Statement ;
}
while ( condition)
Example
<html>
<head>
<title>Do While loop</title>
</head>
<body>
<script>
var x = prompt ("Enter value");
do{
document.write(x);
x++;
}
while(x <20)
</script>
</body>
</html>
Please share
JavaScript Syntax
Where do you place JavaScript in HTML document
JavaScript Variables
JavaScript Strings: How to create and manipulate
JavaScript If, If else, If else if statement
JavaScript Function: How to define and call a function
How to generate output in JS
JavaScript Switch case
Comments
Post a Comment