JavaScript Loops Expanded

Michael Abe
2 min readNov 4, 2021

--

As we have discussed previously, loops and iterating are incredibly important aspects of coding overall. JavaScript is no exception to this concept and we use loops quite frequently. Loops are great to keep things moving along in an orderly manner but sometimes there needs to be an exception to the loop that you are using. In certain situations, we could potentially write that condition in an if statement but another option that we can potentially explore is the JS “break” statement.

The break statement in JavaScript can be used in a few different ways but the one that we will focus on today is to break out of a loop. If you wanted to stop a for loop at a specific point you could so the following:

If we took the “break” statement out of line 2 in the for loop above, we would simply get the singular number “5” logged in the console. Since our condition is simply saying that if “i” (incrementing number in our for statement) is absolutely equal to “5” we want to log i at that point to the console. By adding the break, we are completely changing the statement to more of an incrementing condition where we get the result seen in the console above. We essentially have a statement that we should do something until the counter (i) reaches “9” but by adding the break, we are effectively jumping out out of that loop as soon as the condition (counter (i) equaling “5”) so we log “0–4” in the console.

Let’s say that you wanted to skip the condition on line 2 of our example and basically log to the console the numbers 0–9 but exclude the number 5 we could substitute the “break” that we used for a “continue”.

As we can see in the example above, we have the desired output and all that it took was changing one word in our condition statement.

These are obviously very basic examples of how the break and continue statements can be used but they display a great foundation that we can use to further customize our code.

--

--