When coding and working through algorithms and code challenges, if I needed to loop over or iterate through something we can use a loop. I wrote an earlier post on using a for loop which is a common loop where we loop while a condition is met and then do something so the condition changes each time. A while loop is similar to this in that we keep looping while a certain condition is true, unlike the for loop which usually has 3 parts the while loop just contains the condition that while true the loop will run. Then inside the loop is where we usually change something about the condition to ensure we aren’t simply running an infinite loop.

Here is a simple example of a while loop in JavaScript:

`let i = 5while (i > 0){  console.log(i)  i--}`

We will get printed to the console:

`54321`

As expected this is a simple example of just the syntax of writing it out because for this we also easily could’ve just used a for loop and achieved the same outcome. It is all the same parts of a for loop just structured differently.

There are cases where the while loop is needed and is better to use than a for a loop. While working on problems where you have two pointers I have found often times there is a good case for using a while loop. Especially if you are looking to compare the two pointers as the condition. And within the loop, you can change one or the other pointer based on a condition. A good example of this and a better use case for the while loop is leetcode 11 finding the container with the max area. The problem provides an area of heights and the width is the distance in the array between the two indexes of the two heights. The area has to hold water so the height used to calculate the area is the smaller of the two heights in the area.

Here is the code for solving this in JavaScript utilizing a while loop:

So in the code, we have our two pointers i and j the start and end of the height array. The way it is set up this while loop will then run until i and j meet(where the area would be 0 and definitely not a max area). We use a while loop to calculate the area between the two indexes and find out if it is the max and set it to the max if it is. Then depending on which height is greater, we move i closer to j (the end) or j closer to i (the start). When i and j meet the loop is over and we have our max area stored in max.

The MDN web docs explain the while loop here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while