create a loop without for in javascript

You can create a loop without for in JavaScript using either the while loop or the do-while loop.

While Loop

The while loop runs as long as the specified condition evaluates to true. Here's an example of a while loop that prints the numbers 1 to 5:

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

Do-While Loop

The do-while loop will first execute the code block once, and then continue to run as long as the specified condition evaluates to true. Here's an example of a do-while loop that prints the numbers 1 to 5:

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

Recursion

Recursion is another way to iterate over a sequence of values without using the for loop. Recursion is the process of defining a function in terms of itself. Here's an example of a recursive function that prints the numbers 1 to 5:

index.tsx
function printNumbers(n) { 
  if (n > 0) { 
    printNumbers(n - 1); 
    console.log(n); 
  } 
}

printNumbers(5); 
117 chars
9 lines

In this example, the printNumbers function calls itself until the argument n is greater than 0. It then prints the value of n before returning to the previous call of the function. The output of this function would be:

index.tsx
1
2
3
4
5
10 chars
6 lines

gistlibby LogSnag