The “while” Loop

It’s been a while

The “while” loop is the first looping structure that we will discuss, it is used to repeat a section of code until a Boolean condition is met. To me, a while loop is just an “if” statement that repeats while it’s boolean expression is true.

Formula for While

As with many ingredients of programming, different languages will represent the while loop in different ways. The formula, however, is almost always the same.

while <boolean-expression> repeat <statements>

As usual I have not used an language specific keyword for the formula so that actual syntax (wording and structure) is going to be different.

So What Does it Look Like for Real?

JavaScript

// To get the results below open your browsers developer tools, 
// hit F12 on the keyboard. Then select the console and you 
// will be able to type the code below

while(<boolean-expression>) {
    <statements>
}

How Does it Work?

When the boolean expression of the “while” loop is evaluated as true, the subsequent statements are executed. Once the statements finish executing, the flow of the program jumps back up to the boolean expression and the process begins all over again. When the expression is finally evaluated as false the statements are skipped over instead of being executed and normal program execution continues. Let’s look at some examples!

JavaScript

var result = 0;
undefined

while(result < 5) {
  result += 1;
}

result;
5

while(false) {
  result = 10;
}

result;
5

But I Want More

Sometimes, you will need to execute the statements in a while loop at least once regardless of the result of the boolean expression. For those cases, we have the “do while” loop. The “do while” loop is the same as the “while” loop in every way except the boolean expression comes after the statements.

Formula for Do While

Again, this is the formula not the language specific syntax

repeat <statements> while <boolean-expression>

So What Does it Look Like for Real?

JavaScript

do {
    <statements>
} while(<boolean-expression>);

How Does it Work?

“Do while” works exactly like a “while” loop but ensures at least one execution of the statements.

JavaScript

var result = 6
undefined

do {
  result += 1;
} while(result < 5);

result;
7

We’re Done

That is all there is to “while” loops. As Always, I hope you learned something from this, but if not please look at some of the other articles as they are more advanced and may lend you some insight in the world of software development.

Leave a Reply

Your email address will not be published. Required fields are marked *