Introduction to JavaScript loops

Introduction to JavaScript loops

Introduction:

So assume a little boy wants to fetch water from a well to fill up a drum and it will take 20 rounds to fill the drum, that means he would have to draw the water 20 times before the water can reach the bream of the drum. That probably would be so exhausting, imagine he had a manual pulley that could be set to any number of times drawing the water from the well for him. Wow that saves a lot of stress right? . That's just how loops work .

  • the pulley is the loop

  • the number of rounds he would have pulled the water himself are called DRY codes(don't repeat yourself )

  • the number of times you set the pulley to are the condition

Definition:

Loops are used in JavaScript to perform repeated tasks based on a condition. Conditions typically return true or false when analysed. A loop will continue running until the defined condition returns false.using Javascript loops, you can perform iterations with only a few lines of code. Iteration is the number of times you want to repeat the task (that number can even be zero).

There are primarily two types of loops in any programming language, These are:

  • Entry Controlled Loops: Any loop where we check the test condition before entering the loop is an entry controlled loop. In these loops, the test condition determines whether the program will enter the loop or not. These include for, while, etc.

  • Exit Controlled Loops: Any loop where we check the test condition after the statements are executed once is an exit controlled loop. In these loops, the test condition determines whether or not the program will exit the loop. This category includes do…while loop.

Different Kinds of Loops

JavaScript supports different kinds of loops and they include:

  • for - loops through a block of code a number of times

  • for/in - loops through the properties of an object

  • for/of - loops through the values of an iterable object

  • while - loops through a block of code while a specified condition is true

  • do/while - also loops through a block of code while a specified condition is true

JavaScript-Loops-1280x720.jpg

images source:data-flair.training/blogs/loop-in-javascript

while-loops:

This loops through a block of code while a specified condition is true. while loop starts by evaluating the condition. If the condition is true, the statement(s) is/are executed. If the condition is false, the statement(s) is/are not executed. After that, while loop ends.

while.png image source:javascripttutorial.net/javascript-for-loop

syntax

while (boolean condition)
{
statements
}

Example:

<script> 

var i = 25;  

while (i<=20)  {  

  document.write(i + "<br/>");  
  i++; 

}  

</script>

For loop:

The for loop is the most compact form of looping. It keeps on repeating until a specified condition evaluates to false. It consists of three important pants.

  • The loop initialization: this is the part of the code that initializes the counter to a starting value(var=1). This statement is written before the statement begins. This expression may optimally declare variables with var or let keywords.

  • The condition: This is the test statement which tests if a given condition is true or not . This expression is evaluated before each loop iteration. If the condition is true the statement will be executed (i < =50)

  • The increment statement: This expression is used to either increase or decrease value on each execution. JavaScript-for-Loop.png

image source:javascripttutorial.net/javascript-for-loop

In a for loop, all three parts are written together on a single line to make it readable and easily maintained. The for loop is used mostly when the number of iterations are known .

syntax

 for(initialization; condition; increment/decrement) 
{
    // Code to be executed
}

Example

<script>
    for(var i=1; i<=5; i++) {
        document.write( i + "<br>");
    }
  </script>

The difference between while and for loop is:

  • the for loop is shorter , cleaner and even more readable in case of multiple lines of code than the while loop .

  • but then the while loop isn't short but it allows you to be flexible with the statement you give it flexible unlike the for loop

  • You must create a new variable in the for loop but that not the case for the while loop.

For-in loop:

This loop is used to iterate through the properties of an object and execute the body of the loop once for the enumerable property of the object. For each distinct property, javascript executes the specified statement. This loop is mostly used in debugging purposely,(since they check properties of data) and storing data.

1_B3sTgE2qSnpdhffrYZl6Mg.png

image source:levelup.gitconnected.com/three-different-wa..

syntax

for(variable in object) {
    // Code to be executed
}

Example

<script>
Var student = {
    Name: “hannah”,
    Age: 25,
    Level: “basic”
}
for(var item in student)
   {
        alert(student[item])
   };
</script>

For-of loop:

This loop is used to iterate over the objects in an iterable object(including array, map, set, arguments object and so on)

syntax

for(variable in object) {
    // Code to be executed
}

Example

<script>

const array = ['Anita', 'Belle', 'Charles', 'Divine'];
for (const item of array) {
    console.log(item)
}

</script>

Between the for-of and the for-in, both iterate over something except the for-in iterates over all enumerable properties of an object while the for-of is more specific to collections such as arrays and objects but does not include all objects.

Do-while loop

A do-loop is similar to the while loop except that in do-loop, the condition is executed after the statement in the loop. This makes it an exit controlled loop. Using the do-while loop, the body of a loop is always executed once before the condition is checked, It makes sure that the code is executed at least once and after execution if the condition is true the loop else the loop terminates but if true, the next iteration loop starts.

do-while-loop-2.png image source:edureka.co/blog/javascript-loops

syntax

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

Example

<script>
Int i=0;
  Do{  
       i+= 1;
       console.log(i);
}      while (i < 5);
</script>

Summary

Hopefully by now you must have understood that looping is a key part of any programming language and and we understand the that there are two types of loops, the exit and entry controlled loops and in order to select the right loops we should consider if the problem faced requires a pre-test or a post-test loop.