Loop in javaScript-tutorial
In JavaScript, loops let us execute a block of code multiple times perfect for tasks like printing numbers, iterating through arrays, or repeating actions until a condition changes.
There are three main types of loops in JavaScript
for loop
Use a for loop when you know in advance how many times you want to repeat a block of code.
Syntax:
Example:
Output
.webp)
While loop
Use a while loop when you do not know exactly how many times you need to loop the loop continues a s long as the condition is true.
Syntax:
Example:
Output
.webp)
do While loop
A do while loop is similar to a while loop, but is always executes the block of code at least once, even if the condition is false initially.
Syntax:
Example:
Output
.webp)
There are three main types of loops in JavaScript
- for loop
- while loop
- do while loop
for loop
Use a for loop when you know in advance how many times you want to repeat a block of code.
Syntax:
for (initialization; condition; update) { // Code to execute}
Example:
<!DOCTYPE html><html>
<body> <script> for (var i = 1; i <= 5; i++) { document.write(i + "<br/>"); } </script></body>
</html>
Output
.webp)
While loop
Use a while loop when you do not know exactly how many times you need to loop the loop continues a s long as the condition is true.
Syntax:
while (condition) { // Code to execute}
Example:
<!DOCTYPE html><html>
<body> <script> var i = 12; while (i <= 14) { document.write(i + "<br/>"); i++; } </script></body>
</html>
Output
.webp)
do While loop
A do while loop is similar to a while loop, but is always executes the block of code at least once, even if the condition is false initially.
Syntax:
do { // Code to execute} while (condition);
Example:
<!DOCTYPE html><html>
<body> <script> var i = 21; do { document.write(i + "<br/>"); i++; } while (i <= 25); </script></body>
</html>
Output
.webp)
Key Point
- Use for when you know the count.
- Use while when the number of loops depends on a condition.
- Use do while to run at least once, even if the condition is false.