JS Tutorial



JS LOOPS


JavaScript Loops

Loops allow you to execute a block of code multiple times, which is useful when you need to repeat actions like traversing arrays or iterating through conditions.

πŸ”Ή Types of Loops:
  • for loop
  • while loop
  • do...while loop

πŸ“Œ for Loop

The for loop is the most commonly used loop to iterate through arrays or perform a block of code a specific number of times.

Syntax

for(initialization; condition; increment/decrement) {
  // code block to be executed
}

Example: Print Numbers 1 to 5

for (let i = 1; i <= 5; i++) {
  console.log(i);
}

πŸ“Œ while Loop

The while loop will continue to run as long as the condition is true. It's useful when you don’t know how many times you need to iterate in advance.

Syntax

while (condition) {
  // code block to be executed
}

Example: Print Numbers 1 to 5

let i = 1;
while (i <= 5) {
  console.log(i);
  i++;
}

πŸ“Œ do...while Loop

The do...while loop executes the code block once before checking the condition. It guarantees the block runs at least once.

Syntax

do {
  // code block to be executed
} while (condition);

Example: Print Numbers 1 to 5

let i = 1;
do {
  console.log(i);
  i++;
} while (i <= 5);

πŸ§ͺ Try It Yourself




Loop output will appear here
πŸ“˜ Summary:
JavaScript offers three different types of loops: for, while, and do...while. Choose the one that fits your needs based on how you want the loop to behave.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review