In this article, you will learn how to use the JavaScript loop statement to create a loop with various options.
The three most common types of loops are
- for
- while
- do...while
for loop
for ([initialization]); [condition]; [final-expression]) {
// statement
}
Here you can try this,
var inputs = document.getElementsByClassName('loopjavascript');
for (var i = 0; i < inputs.length; i++) {
console.log(inputs[i].value);
}
<input type="text" name="test1" class="loopjavascript" value="loopjavascript 1">
<input type="text" name="test1" class="loopjavascript" value="loopjavascript 2">
<input type="text" name="test1" class="loopjavascript" value="loopjavascript 3">
<input type="text" name="test1" class="loopjavascript" value="loopjavascript 4">
while loop
while (condition)
{
statement(s);
}
Here you can try this,
var i = 1;
while (i < 10)
{
console.log(i);
i++; // i=i+1 same thing
}
Output:
1
2
3
4
5
6
7
8
9
Do..while loop
loops through a block of code once; then the condition is evaluated. If the condition is true, the statement is repeated as long as the specified condition is true.
do {
// Code to be executed
}
while(condition);
Here you can try this,
var i = 1;
do {
document.write("<p>The number is " + i + "</p>");
i++;
}
while(i <= 5);