You can create a loop without for in JavaScript using either the while
loop or the do-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.tsx102 chars6 lines
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.tsx132 chars6 lines
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.tsx117 chars9 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.tsx10 chars6 lines
gistlibby LogSnag