javascript
  1. javascript-loop

JavaScript Loop

Loops are used in programming to execute a block of code repeatedly until a certain condition is met. In JavaScript, there are three types of loops: for, while, and do-while. Each type has its own syntax and use case.

Syntax

For Loop

for (let i = 0; i < n; i++) {
  // code to execute
}

While Loop

while (condition) {
  // code to execute
}

Do-While Loop

do {
  // code to execute
} while (condition);

Example

For Loop

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

While Loop

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

Do-While Loop

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

Output

For Loop

0
1
2
3
4

While Loop

0
1
2
3
4

Do-While Loop

0
1
2
3
4

Explanation

For Loop

A for loop is used when you know the number of times you want to execute a block of code. The loop starts with an initial value of a variable (in this case, i is set to 0) and continues as long as the condition is true (in this case, i is less than 5). Each time the loop executes, the value of i is incremented by 1.

While Loop

A while loop is used when you don't know the number of times you want to execute a block of code. The loop continues as long as the condition is true (in this case, i is less than 5). Each time the loop executes, the value of i is incremented by 1.

Do-While Loop

A do-while loop is similar to a while loop, but the code block is executed at least once before checking the condition. The loop continues as long as the condition is true (in this case, i is less than 5). Each time the loop executes, the value of i is incremented by 1.

Use

Loops are used in many different scenarios in programming. Some common use cases include:

  • Iterating over an array or object
  • Checking user input until it's valid
  • Repeating an action until a certain condition is met
  • Generating a sequence of numbers or characters

Important Points

  • Be careful of infinite loops, which can crash your program.
  • Always make sure the loop will eventually terminate.
  • Use the correct loop for the job – for loops are for a known number of iterations, while loops are for an unknown number of iterations, and do-while loops are for at least one iteration.

Summary

In JavaScript, loops are used to execute a block of code repeatedly until a certain condition is met. There are three types of loops – for, while, and do-while – each with its own syntax and use case. Loops are used in many different scenarios in programming and can be incredibly useful when used correctly.

Published on: