We’ll be continuing with loops by learning about the while loop. The while loop is another way of looping through a block of code while a certain condition is true. Before we get started, let’s talk about iterations for a second
An iteration is the technical term for a process that repeats itself. In the programming world, every time a loop successfully runs, then that’s considered an iteration.
Creating A While Loop
Clear out your script and update your code to this.
var i = 0;
var total = 0;
while ( i < 10 )
total += 10;
alert( total );
A couple of things going on here. We create 2 variables called i and total. Both of these values are assigned 0. Next, we create a while loop. A while loop is structured similar to the for loop. There’s one main difference. A while loop does not have an initializer and does not have an increment. It’s made up of 2 parts. The first part is inside the parenthesis. This is where you insert the conditional. If this condition is true, then the loop runs. Inside the curly brackets is the second part. This is where you execute all your code.
Since you don’t have an increment or an initializer, we have to create these outside and inside the loop. Inside our loop, we add 10 to the variable total and increment i by 1. Our loop will run as long i is less than 10. Lastly, we alert the final value of total.
While Loops vs For Loops
Both of these loops are useful for certain situations. A for loop is mainly used for situations where you know exactly how many times you want a loop to run. A while loop is used when you’re uncertain when you want to break out of it. We haven’t talked about objects yet, but soon you’ll see how more flexible a while loop can be in unknown situations.
You’ll find yourself using both loops. You’re more than welcome to stick to one type of loop. In our next tutorial, we’ll talk about a variation of the while loop.