JavaScript: Loops
Loops allow you to create repeating JavaScript statements. A loop processes the statement over and over until you tell it to stop. There are several types of loops.
While Loops
The While loop is the most basic loop. To start a while loop, rather than using if
to begin your statement, as with conditional statements, you write while
. Here's an example:
This script will repeat itself infinitely as long as x is less than 100. You need to tell it to stop looping.
You can stop the loop in a couple of ways. One way is to increment the variable so that at some point, the condition is no longer met:
Now the script will repeat 99 times. With each iteration, x increments by 1. Once x gets to 100, the code won't execute because the condition ( x > 100 )
isn't met.
Do ... While Loops
There's another way to stop a loop. Rather than beginning with while
, you can use the "Do ... While" format:
The Do ... While loop differs in that you put the condition after the code block. This means the code block will run at least once regardless of the condition. Once the code block runs and the condition is asked, the loop continues only if the condition is met.
For Loops
Loops typically have three components: an index, a condition, and an increment to the index. The index is a variable you use to start counting your loop. Written out the long way, the statement would look as follows:
Because loops are so common, you can write this statement in a more abbreviated way using the for
loop. With the for
loop, you start the statement with the word for
. You then insert the conditions and increment value in parentheses separated by semicolons. You then add the code block. Here's an example:
Break and Continue
You can stop a loop using the words break
and continue
. Break
exits the loop, whereas continue
stops the current command and rechecks the conditions to see if the loop can start again at the top.
Here's an example with break
:
About Tom Johnson
I'm an API technical writer based in the Seattle area. On this blog, I write about topics related to technical writing and communication — such as software documentation, API documentation, AI, information architecture, content strategy, writing processes, plain language, tech comm careers, and more. Check out my API documentation course if you're looking for more info about documenting APIs. Or see my posts on AI and AI course section for more on the latest in AI and tech comm.
If you're a technical writer and want to keep on top of the latest trends in the tech comm, be sure to subscribe to email updates below. You can also learn more about me or contact me. Finally, note that the opinions I express on my blog are my own points of view, not that of my employer.