create loop in javascript

There are different ways to create loops in JavaScript, but the most common ones are:

  1. For loop: This loop allows you to execute a block of code multiple times based on a defined condition.
index.tsx
for (initialization; condition; increment/decrement) {
    // block of code to be executed
}
93 chars
4 lines

Example:

index.tsx
for (var i = 0; i < 5; i++) {
    console.log("Number:" + i);
}
64 chars
4 lines

Output:

index.tsx
Number:0
Number:1
Number:2
Number:3
Number:4
45 chars
6 lines
  1. While loop: This loop executes a block of code as long as a specified condition is true.
index.tsx
while (condition) {
    // block of code to be executed
}
58 chars
4 lines

Example:

index.tsx
var i = 0;
while (i < 5) {
    console.log("Number:" + i);
    i++;
}
70 chars
6 lines

Output:

index.tsx
Number:0
Number:1
Number:2
Number:3
Number:4
45 chars
6 lines
  1. Do while loop: This loop is similar to the while loop, but it executes the block of code at least once before checking the condition.
index.tsx
do { 
    // block of code to be executed
} 
while (condition);
64 chars
5 lines

Example:

index.tsx
var i = 0;
do {
    console.log("Number:" + i);
    i++;
} while (i < 5);
74 chars
6 lines

Output:

index.tsx
Number:0
Number:1
Number:2
Number:3
Number:4
45 chars
6 lines

gistlibby LogSnag