JavaScript: Anatomy of Loops.

JavaScript: Anatomy of Loops.

In JavaScript, just as in other programming languages, we use loops to read or access the items of a collection. The collection can be an array or an object. Every time the loop statement cycles through the items in a collection, we call it an iteration. Design patterns can be challenging as a beginner developer hence understanding how syntax work is a first step towards excelling at programming and on tests. Therefore, emphasis is often placed on building muscle memory from constant practice to ensure concepts stick and can be called up from first principle when needed.

In this article, we’ll learn about loops in JavaScript from first principle. We’ll explore the different types of loop statements and their usage, the syntax, and examples of how it works.

What are loops?

A loop is basically repeating a sequence of instructions until you reach a certain stated condition. Loops iterate some code until a set condition is met. We use a loop when we have some logic which we need to happen repeatedly. A good number of times, we intend to repeat instructions with a code such as counting multiple items or accessing some information a certain number of times.

Loops are used to read or access the items of a collection. The collection can be an array, a map, a set, strings, or an object. An iteration is when the loop statement goes through a cycle of the elements in a collection.

The three frequently used types of loops in JavaScript are the for loop, while loop and the do-while loop although there are other variations of the for loop which includes the for-of loop and the for-in loop.

  1. For loops
  2. For of loops
  3. For in loops.
  4. While loops
  5. Do while loops

For loops

A for loop enables a particular set of conditions to be executed repeatedly until a condition is satisfied. For for-loops, we know exactly the number of times the loop will execute before the loop even begins. For example, if we want to check the grade of every student in the class, we loop from 1 to that number say n representing the number of students. The syntax of a for loop is shown below;

for (initialization; condition; iteration/counts) {
  //code block to be executed
}

There are three commands in executing a for-loop;

  • Initialization: describes the starting point of the loop, where the loop variable is initialized with a starting value. A loop variable or counter is simply a variable that controls the flow of the loop.
  • The condition, which is tested until when the loop is repeated.
  • Iteration: This where the increment or decrement statement lies and is also known as the update statement, it is usually the iteration counter (increment/decrement).

for loops flowchart

For-Loops.JPG

Example of a for loop

for (let i = 0; i <= 10; i++){
    console.log("i is not", i)
 }

Output image.png

For-Of Loops

This is often used for iterable properties (elements that can be counted). Each value in the array is substituted based on the iteration and printed out. This can also be used on strings. This will output the values of the array’s indexes in order, if the object is an array. If the object contains key-value pairs, it will print out every value that exists.

The for-of loop does not guarantee that keys within key-value pairs will always be accessed in the same order. Syntax of a for-of loop is as shown below;

for (let i of object) {
    console.log(object[i]);
}

Example of for-of loops for arrays

const iterable = [10, 20, 30]

for (const value of iterable) {
console.log (value)
}

Output image.png

Example of for-of loops for strings

const firstName = "Onyeka"
for (const car of firstName) {
console.log ("character is: ", car);
}

Output image.png

This works for iterables such as arrays, maps, sets, and strings.

For-In Loops

This type of loop only iterates the enumerable properties of an object and ultimately its values which are the object’s own properties. Basically, looping over an objects elements one by one. It can also be useful for debugging but should be avoided when iterating arrays or making changes to the object. The difference between the for-of loop and the for-in loop is, while for-of loop returns values, the for-in loop returns keys or indexes. The syntax of a for-in loops.

for (let i in object) {
    console.log(object[i]);
}

This prints out the keys in the object.

Example of a for-in loop

const user = {
    name: "John",
    age: 20,
    city: "Lagos",
    };

    for (const key in user) {
    console.log(key)
    console.log(`The key is: ${key} and the value is: ${user[key]}`)
    }

Output image.png

This type of for-loop only works for objects.

While loops

While loops are used when we do not know the number of times the code needs to be executed. Hence, the instructions are repeated an unknown number of times. As far as the loop returns a boolean value of true, the code inside it will keep repeating. Although it is quite important to set the condition to false to stop the 'while' loop, otherwise, the code will execute infinitely. The while loop also works in decrement situations. The syntax of a while loop is shown below;

while (condition) {
  // code block to be executed
}

Flowchart of a while-loop

image.png

Example of a while-loop

let i = 0; //initialization
while (i < 3) //condition
{
console.log(i);
i++;
} //block of code to be executed wrapped in curly brackets

Output image.png

Sequence:

  • Declare the variable
  • Check condition
  • Execute code

Do-while Loops

The do-while loop executes a block of code before checking if the condition is true. And repeats the loop as far as the condition remains true. Unlike the for and while loops which check the condition at the beginning of the loop the do-while loop runs the code at least once before checking the condition. Often, in a menu-driven program, when actions are supposed to be taken repeatedly based on the user input, we need a do-while loop to understand which action the user wants to take. In such cases, the control breaks out of the loop when the user input equivalents to an exit command. Syntax of a do-while;

do {
  // code block to be executed
}
while (condition);

Flowchart of a do-while loop

image.png

Example of a do-while loop

let j = 1 //initialization
do {
console.log(j);
j++; //executes code with a counter once
} while (j < 3) //checks condition

Output image.png

In conclusion, loops are quite important in programming as they help us have better, cleaner codes. If we did not use loops, we will have to repeatedly write out codes we want to run, and this will be contradicting the DRY (don’t repeat yourself) principle which allows for cleaner, readable code. I hope you’ve found the above examples and explanations useful.

As always, please, shoot me a tweet with questions and suggestions.

I do hope you found this useful, cheers!

Follow the link for further reading