loop in javascript

In JavaScript, there are different types of loops available to perform repetitive tasks.

One of the most commonly used loop is the for loop. It repeats a block of code for a specific number of times. Here's an example of a for loop:

index.tsx
for(let i = 0; i < 5; i++) {
  console.log(i);
}
49 chars
4 lines

This loop will execute five times and output the values of i from 0 to 4.

Another type of loop is the while loop. It repeats a block of code while a condition is true. Here's an example of a while loop:

index.tsx
let i = 0;
while (i < 5) {
  console.log(i);
  i++;
}
54 chars
6 lines

This loop will execute five times and output the values of i from 0 to 4.

Another type of loop is the do-while loop. It is similar to the while loop, except that it always executes the block of code at least once, even if the condition is false. Here's an example of a do-while loop:

index.tsx
let i = 0;
do {
  console.log(i);
  i++;
} while (i < 5);
58 chars
6 lines

This loop will execute five times and output the values of i from 0 to 4.

Loops are useful when you need to perform repetitive tasks, such as iterating through an array or processing user input.

gistlibby LogSnag