Loops
- In Javascript, loops are used to execute blocks of code repeatedly.
Loops in JS:
- for loop
- while loop
- do-while loop
for loop:
- when you know the number of times you want to repeat a block of code, then we use for loop.
Syntax:
for (initialization; condition; update) {
// Code to be executed
}
Example:
<!DOCTYPE html>
<html>
<body>
<script>
for (i = 1; i <= 5; i++) {
document.write(i + "<br/>")
}
</script>
</body>
</html>
Output:
1
2
3
4
5
While Loop:
- you want to continue iterating as long as a specific condition is true. Then while the loop is used
- The loop will execute as long as the condition remains true.
Syntax:
while (condition)
{
code to be executed
}
Example:
<!DOCTYPE html>
<html>
<body>
<script>
var i = 12;
while (i <= 14) {
document.write(i + "<br/>");
i++;
}
</script>
</body>
</html>
Output:
12
13
14
do while loop:
- The do...while loop is similar to the while loop, but it guarantees that the code block is executed at least once, even if the condition is false.
Syntax:
let i = 0;
do {
// Code to be executed in each iteration
i++;
} while (i < 5);
Example:
<!DOCTYPE html>
<html>
<body>
<script>
var i = 21;
do {
document.write(i + "<br/>");
i++;
} while (i <= 25);
</script>
</body>
</html>
Output:
21
22
23
24
25