JavaScript while loop

Michael Abe
2 min readOct 28, 2021

--

Last week we talked about the for loop in JavaScript. The for loop is a great way to write a loop that operates for a predetermined amount. This can be especially effective in something like a counter, when we know the total amount of times that we want something to happen we can combine that with an incrementor as a way to determine a good stopping point. Sometimes, we don’t know specifically how may times we want something to run or maybe we are making something that needs to be dynamic and the needs of how many times it runs is determined on another factor. The best way of dealing with this in my opinion is to use the JavaScript “while” loop.

The basic principle in a while loop is that something runs until a condition is no longer true. In the for loop we run it until a condition is met. In a while loop, we run it while the condition is still in effect. The basic syntax for a while loop is:

This is a pretty self explanatory situation. While a condition is being met, we run our code. If we wanted to make an incrementing counter based condition using a while loop, it would look similar to the following

As we can see, the loop ran as long as our condition was met. In this case, the condition that we created was that the integer was less than 5.

There are tons of more interesting and complex ways to impalement the ‘while’ loop in JavaScript. This is just the foundation of one of the more important aspects.

--

--