While loops

A way to repeat something.

While loops

They allow us to repeat the same code multiple times.

while (condition) {

// your code in the body

}

While the condition is true, the code from the loop body will run.

let s = 0;

while (s < 5){

console.log(s);

s++;

}

The above will print out 0 - 4.

We start out setting s equal to 0.

Each iteration we check to see if it is less than 5.

If so print it out and then increment by one.

do...while

We can move our check to the end of the loop body using the do...while.

This ensures the body / your code will run at least once.

Since the check is after our code, it doens't matter if the first iteration is true or false.

do {

// your code

} while

To show exactly what I mean.

let j = 7;

do{

console.log(j);

j++;

} while (j<1);

This prints a out 7.

Then j is checked against the conditional 1.

It is greater, so nothing else is done.

for loop

Looks like this:

for (begin; condition; step) {

// your code

}

An example to print out 1 through 10.

console.log("Start for loop.");

for (let t = 0; t < 11; t++){

console.log(t);

}

Here is what's happening...

The i = 0 is going to execute once when entering the loop.

Condition: i < 3 is going to be checked before every loop iteration. If it's false, the loop stops.

t++ is executed after the body on each iteration.

console.log(t) in this case is our code body that executes when the condition is true.

That's why 10 is the last digit that is printed.

The condition becomes false and the loop ends.

Break

There is another way to force an exit to a loop.

You use the break keyword/directive.

Check the JS file and uncomment lines 25-32 for the example.

Continue

Continues is kind of like the break.

It doesn't stop the whole loop, it just stops the current iteration and forces a new one.

Here we'll use it to print out only even values from 1- 10, not including 10.

for (let k=0; k < 10; k++){

//If this evaluates to true - skip the console call

if (k % 2 == 1) continue;

console.log(k);

}

Here is what's happening.

For odd values of k, the continue directive stops its execution (it does not run the console.log(k)) and gives control back to the next iteration of the for loop with the incremented value.

We're only checking for even numbers so, it's going to be even and print this time.

Labels

In addition to breaks and continue, we can use labels with them.

This gives us the ability to jump out of nested loops.