In JavaScript, there are three ways to write loops: for
, while
, and do-while
. Each loop has its own syntax and may be better suited for different situations.
for
LoopThe for
loop is used when you know exactly how many times you want to iterate. It has the following syntax:
index.tsx72 chars4 lines
The initialization
is usually a variable declaration that initializes the loop counter.
index.tsx75 chars4 lines
while
LoopThe while
loop is used when you do not know how many times you want to iterate, but you know the condition for when you want to stop iterating. It has the following syntax:
index.tsx47 chars4 lines
The condition
is any JavaScript expression that evaluates to true
or false
. The code block inside the loop will continue to execute as long as the condition is true
.
index.tsx79 chars6 lines
do-while
LoopThe do-while
loop is similar to the while
loop, but it always executes the code block at least once. It has the following syntax:
index.tsx51 chars4 lines
The condition
is evaluated after the code block has executed. If the condition is true
, the code block will execute again.
index.tsx83 chars6 lines
Each type of loop has its own strengths and weaknesses, so it's important to choose the right one for your needs.
gistlibby LogSnag