JavaScript Loops - Do...while loops, for...in loops and more

JavaScript Loops - Do...while loops, for...in loops and more

As JavaScript developers, loops are something that we will encounter quite frequently. Loops are a programming tool that is used to repeat a set of instructions. If we encounter a repetitious task, we will write a loop. Loops are very handy to have in your developer toolbelt. Looping in JavaScript is an important feature that helps us to create efficient code.

In this article, we will learn about the several types of loops, do...while loops, for...in loops and for...of loops. We will also learn when to use them and how they work. Even though the syntax may be a little different they can perform the same actions. There are many different kinds of loops but they essentially do the same thing which is repeat an action.

Do...while loops

Do...while loops will execute before finding out if the statement is true or false before checking for the condition . Do...while loops will check for the condition after the first iteration is ran. Then it will continue as long as the condition is true. We use do...while loops when we want to execute the code at least once. Be careful though, this is a quick pathway for infinite loops.

let mangoes = ' ';
let i = 0;

do {
i = i + 1;
mangoes = mangoes + i;
} while (i < 7);
console.log(`How many fruits are there? ${mangoes}`)
//expected mangoes = 1234567

Two things are happening here so let's break it down:

  • The do statement body will run first before checking the while condition.
  • This is why we get 7 at the end even though the while statement shows i < 7.
  • It will run at least once each time.

What to avoid with do while loops

At some point you will come across an infinite loop, be careful because it could crash your computer or browser. Always make sure that you have at least one statement in the loop that changes the value of the variable. Otherwise the condition will always return true and create an infinite loop. It is good to be aware of infinite do...while loops so you can avoid them in the future.

For...in loops

For...in loops are used to loop through property names of an object. When trying to use the for...in statement to iterate an object, the iterated properties are represented by the variable name. It is important to remember that objects are made up of properties and values. To demonstrate this we will make a simple island object with a few property:value pairs.

const island = {
  Eleuthera: "pineapples"
  catIsland: "crab"
  Inagua: "flamingos"
}

By using the for...in loop, we can access each of the property names.

for(let propertyName in island){
console.log(propertyName)

//Output:
// 'Eleuthera'
// 'catIsland'
// 'Inagua'

Here is the syntax for a for...in loop. Let us break down the process of how this statement is ran.

  • First we declare the loop using the keyword let
  • Next, we use the variable propertyName. which will iterate all of the property names in the object. Remember that the variable can be named whatever you want it to be.
  • The name of the object must be stated so the for...in statement knows what it is looping through. So, in this case the object name is island.

  • Lastly, the property names of the island object gets printed to the console.

For of loops

For...of loops statement iterates through items in a collection such as an array. It also loops through iterable objects like built in strings, arrays-like objects (.map() and .set()).

const beach = ['Barbary', 'Lucaya', 'Fortune']

for(const favBeaches of beach){
console.log(favBeaches)
}

//Expected Output:
//'Barbary'
//'Lucaya'
//'Fortune'

In this example we declared an array named beach and used a for...of loop to do the following:

  • Firstly we declared the variable using const.
  • On each iteration of the variable favBeaches, a value of a different property is assigned.
  • We now see that the output of the for...in loop printed the values of the beach array to the console.

Example 2: Iterate over a String

let country = 'Bahamas'

for(let value of country){
console.log(value)
};
//'B'
//'A'
//'H'
//'A'
//'M'
//'A'
//'S'

Lets breakdown this second example:

  • We declare the variable country which holds the string 'Bahamas'

  • Inside the for...of loop we have assigned the value of the property that will be iterated to the value variable.

  • The country object will have its properties iterated inside the for...of loop.

  • Finally, inside the for...of loop body we have a console.log() that will print out each value inside the country string.

Difference between for...of loop and for...in loop

At this point you are wondering when does one want to use the for...in loop or for...of loop. Well that depends on what you are trying to accomplish. The for...in loop should be avoided when iterating arrays or making changes to objects. One way to tell the difference between for...in loop and for...of loop is to understand what each statement returns. The for...in loop returns properties or indexes while the for...of loop returns values.

let arr = [4,6,8];
arr.greet = 'hello';

for(let i in arr){
console.log(i);
}

//Expected Output
//'0'
//'1'
//'2'
//'greet'


for(let i of arr){
console.log(i);
}

//Expected Output
// 4
// 6
// 8

Lets point out the differences between the two loop statements:

  • In the for...in loop what we got back from the console is the numeric indexes of the array. This is why we see '0', '1', '2' instead of 4,6,8.

    • '0' is the index of 4
    • '1' is the index of 6
    • '2' is the index of 8
  • The the for...in loop also returns user defined properties. This is why we see 'greet' logged to the console as well.

  • The for...of loop will log to the console what we expect. Which is all the items in the array [4,6,8]. 'Hello' is not in the array, so it will not be logged to the console. Remember that we said it is the value of the user defined property.

Conclusion

Today we learned about:

  • Do...while loops which are used when you want to find out if a statement is true before checking the condition.
  • How to avoid infinite do...while loops.
  • Understanding the similarities and differences between for...in loops and for...of loops.