20 Feb JavaScript Loops
Loops in JavaScript are used to execute a block of code more than once. This is done to avoid writing the code multiple times. The following are the loops in JavaScript:
- while loop
- do-while loop
- for loop
The while loop
In the while loop, the block of code executes only when the condition is true. It executes if the condition is true. The following is the syntax of the while loop in JavaScript:
1 2 3 4 5 |
while (condition) { // code executes if the condition is true } |
Let us see an example to implement the while loop in JavaScript:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<!DOCTYPE html> <html> <body> <h1>The While Loop</h1> <h2>Displaying Marks</h2> <p id="test"></p> <script> let marks = ""; let i = 95; while (i < 100) { marks += "<br>Marks = " + i; i++; } document.getElementById("test").innerHTML = marks; </script> </body> </html> |
Output
The do-while loop
The do-while loop is the same as while, but the do-while executes the statement first and then the condition is tested. This would mean even in case of a false condition; the loop gets executed at least one time.
The following is the syntax of using the do-while loop in JavaScript,
1 2 3 4 5 6 |
do { // code } while(condition) |
The following is an example showing the usage of the do-while loop in JavaScript,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<!DOCTYPE html> <html> <body> <h1>The do-while Loop</h1> <h2>Displaying Marks</h2> <p id="test"></p> <script> let marks = ""; let i = 95; do { marks += "<br>Marks = " + i; i++; } while(i < 100) document.getElementById("test").innerHTML = marks; </script> </body> </html> |
Output
The for loop
The for loop is a loop that executes a specified number of times. Under this, initialize, test, and increment loop counter in a single line, unlike the while and do-while loop.
The syntax of for loop shows the usage of the loop counter, its initialization, as well as the condition:
1 2 3 4 5 6 |
for (initialize loop counter; test loop counter; loop counter increment) { // Code } |
Let us see an example to implement the for loop in JavaScript:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<!DOCTYPE html> <html> <body> <h1>The for Loop</h1> <h2>Displaying Marks</h2> <p id="test"></p> <script> let marks = ""; let i; for( i = 95; i < 100; i++ ) { marks += "<br>Marks = " + i; } document.getElementById("test").innerHTML = marks; </script> </body> </html> |
Output
No Comments