Loops are an important part of programming languages. They give you the ability to execute the same code block over and over which keeps your code smaller and more readable.

If you find yourself copy and pasting the same code for the purpose of executing them multiple times, there's a chance loops might be useful for you.

In this lesson, we'll take a look at the different kinds of loops in JavaScript and also loop control for flow.

For Loop

A for loop is a loop that contains three major parts.

  1. Initial Value: This is the value assigned to the variable that will keep track of the progression in the loop, usually called i.
  2. Condition: This is the conditional that will get re-evaluated to check if the code inside the loop should run again.
  3. Iteration: This is how you advance in progress every time you complete one loop.

A common way to demonstrate for loops is counting from 1 to 10.

JAVASCRIPT
for (let i = 1; i <= 10; i++) { console.log(i); }
HTML
1 2 3 4 5 6 7 8 9 10

Let's break down what's going on here.

First, we create a variable called i and initialize its value to be 1.

JAVASCRIPT
let i = 1;

Second, we say "hey, as long as the variable i is less than or equal to 10, you're good to loop again".

JAVASCRIPT
i <= 10

Finally, after the code inside the loop executes, we want to increment the value of i.

JAVASCRIPT
i++

Put this all together, and what we're saying is this:

"Start i at 1, log it to our console, increment the value of i by 1, then check that we're still equal to or less than 10, if so, repeat. Once the value of i reaches 11, we can stop looping since 11 is greater than 10."

While Loop

A while loop is a kind of loop that takes a single condition and evaluates it. If it evaluates to true, it will run again, otherwise if it evaluates to false it stops running.

Let's look at the same situation we tackled above but using a while loop instead.

JAVASCRIPT
let i = 1; while (i <= 10) { console.log(i); i++; }
HTML
1 2 3 4 5 6 7 8 9 10

While the output is exactly the same, we accomplished it with a while loop and not a for loop, but let's break this down as well.

First, we create a variable called i and initialize its value to 1.

JAVASCRIPT
let i = 1;

Second, we say "while i is still less than or equal to 10, loop once more".

JAVASCRIPT
while (i <= 10) {

Finally, the code inside the loop simply logs the variable i then increments its value.

JAVASCRIPT
console.log(i); i++;

Eventually, the value of i will exceed 10, causing the loop to terminate.

Do While Loop

A do while loop is very similar to a normal while loop except that the block of code being looped over is guaranteed to run at least once.

This is because it first does the code inside the loop, then checks the condition to determine if it needs to loop again or not.

Consider the situation where you're really hungry and so you bought a family-sized bag of Doritos. They come with 100 chips and since you're starving, each time you go to grab some, you pull out 20 at a time.

Here's how you would demonstrate this using a do while loop.

JAVASCRIPT
let doritos = 100; do { console.log("With " + doritos + " Doritos left, I can eat."); doritos -= 20; } while (doritos > 0); console.log("My Doritos are gone now. I am sad. :(");
HTML
With 100 doritos left, I can eat. With 80 doritos left, I can eat. With 60 doritos left, I can eat. With 40 doritos left, I can eat. With 20 doritos left, I can eat. My Doritos are gone now. I am sad. :(

First, we create a variable to hold how many Doritos are in the bag, and initialize it to 100 chips.

JAVASCRIPT
let doritos = 100;

Second, since we just opened the bag, we know there are chips inside and so we immediately eat some. Since we eat 20 chips at a time, so we can subtract it from the total.

JAVASCRIPT
do { console.log("With " + doritos + " doritos left, I can eat."); doritos -= 20; }

Now that we have eaten some for the first time, we can now check if there are Doritos left in the bag, and we do so with this conditional:

JAVASCRIPT
while (doritos > 0);

While we still have some Doritos in the bag, we are free to go in for more. Eventually, we will run out of Doritos, and that conditional will evaluate to false.

Once that happens, we no longer loop again because we ran out of Doritos to eat.

For In Loop

A for in loop iterates through the properties of an object and the positions in an array.

Here is iterating through a small array, printing out all the values inside it.

JAVASCRIPT
let colors = ["red", "white", "blue"]; for (let i in colors) { console.log(colors[i]); }
HTML
red white blue

All the values inside the colors array were printed, one on each line.

Now, here is a for in loop iterating over the properties of an object:

JAVASCRIPT
let person = { name: "Tom", weight: "150", age: 40 }; for (let property in person) { console.log("This person's " + property + " is " + person[property] + "."); }
HTML
This person's name is Tom. This person's weight is 150. This person's age is 40.

Like with before, the for in loop iterated over what is inside the person object. Each property was printed out on a separate line along with the value. This is a very common way to iterate over objects.

Break

While you are inside of a loop of any kind, JavaScript allows you to terminate the loop whenever you want via the break statement.

Let's try it by counting to 10 like before, but breaking after we output 5.

JAVASCRIPT
for (let i = 1; i <= 10; i++) { console.log(i); if (i == 5) { break; } }
HTML
1 2 3 4 5

This for loop would have printed out every number from 1 to 10, but we told it to break out of the loop if i were equal to 5.

Once that was the case, the loop terminated, and we were left with just the numbers from 1 to 5.

Continue

With the continue statement, you can tell the browser to continue on to the next loop, without finishing the rest of the code block.

Let's say while printing the numbers from 1 to 10, you didn't want the numbers 3 and 7 to appear.

JAVASCRIPT
for (let i = 1; i <= 10; i++) { if (i == 3 || i == 7) { continue; } console.log(i); }
HTML
1 2 4 5 6 8 9 10

This time, before outputting anything, we first check if i is equal to either 3 or 7. If so, we continue to the next iteration, otherwise, we print out the value of i.

Resources

Next Lesson »
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.