A while loop is used to repeat a block of code as long as the specified condition is true. In JavaScript, the syntax for a while loop is as follows:
index.tsx53 chars4 lines
The condition
is checked before each iteration of the loop. If it is true, the code block inside the loop will be executed. The loop will continue to iterate as long as the condition
remains true.
Here's an example of a while loop that prints the numbers 0 to 4 to the console:
index.tsx54 chars6 lines
In this example, the condition
is i < 5
, which means the loop will continue to iterate as long as i
is less than 5. The i
variable is incremented by 1 in each iteration using the i++
shorthand for i = i + 1
. The output of this code will be:
index.tsx10 chars6 lines
gistlibby LogSnag