create a loop in venilla js in javascript

You can create a loop in JavaScript using the for loop, the while loop, or the do-while loop. Here's an example of each:

  1. for loop:
index.tsx
for (let i = 0; i < 10; i++) {
  console.log(i);
}
51 chars
4 lines

This loop will start at i = 0, and continue as long as i < 10. It will run the code inside the curly braces for each iteration of the loop, in this case, just logging the value of i to the console. After each iteration, it will increment i by 1.

  1. while loop:
index.tsx
let i = 0;

while (i < 10) {
  console.log(i);
  i++;
}
56 chars
7 lines

This loop will do the same thing as the for loop above, but instead of using the for syntax, it uses a while loop. It starts with i = 0, just like before, and will continue as long as i < 10. Each iteration, it checks the condition again, and if it's still true, it runs the code inside the curly braces and increments i by 1.

  1. do-while loop:
index.tsx
let i = 0;

do {
  console.log(i);
  i++;
} while (i < 10);
60 chars
7 lines

This loop is similar to the while loop, but it runs the code inside the braces at least once before checking the condition. So in this case, it will log 0 to the console no matter what, and then it will continue looping as long as i < 10.

You can choose which loop to use depending on your specific use case. The general syntax for each loop is as follows:

index.tsx
// for loop
for (initialization; condition; increment/decrement) {
  // code to run for each iteration
}

// while loop
while (condition) {
  // code to run for each iteration
}

// do-while loop
do {
  // code to run for each iteration
} while (condition);
258 chars
15 lines

Remember to use semicolons to separate the different parts of the loop header.

related categories

gistlibby LogSnag