write a loop in javascript

In JavaScript, there are three ways to write loops: for, while, and do-while. Each loop has its own syntax and may be better suited for different situations.

The for Loop

The for loop is used when you know exactly how many times you want to iterate. It has the following syntax:

index.tsx
for (initialization; condition; increment) {
  // code to be executed
}
72 chars
4 lines

The initialization is usually a variable declaration that initializes the loop counter.

index.tsx
for (let i = 0; i < 10; i++) {
  console.log(i); // prints numbers 0 - 9
}
75 chars
4 lines

The while Loop

The while loop is used when you do not know how many times you want to iterate, but you know the condition for when you want to stop iterating. It has the following syntax:

index.tsx
while (condition) {
  // code to be executed
}
47 chars
4 lines

The condition is any JavaScript expression that evaluates to true or false. The code block inside the loop will continue to execute as long as the condition is true.

index.tsx
let i = 0;
while (i < 10) {
  console.log(i); // prints numbers 0 - 9
  i++;
}
79 chars
6 lines

The do-while Loop

The do-while loop is similar to the while loop, but it always executes the code block at least once. It has the following syntax:

index.tsx
do {
  // code to be executed
} while (condition);
51 chars
4 lines

The condition is evaluated after the code block has executed. If the condition is true, the code block will execute again.

index.tsx
let i = 0;
do {
  console.log(i); // prints numbers 0 - 9
  i++;
} while (i < 10);
83 chars
6 lines

Each type of loop has its own strengths and weaknesses, so it's important to choose the right one for your needs.

gistlibby LogSnag