JavaScript - SPLessons

JavaScript Loops

Chapter 10

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

JavaScript Loops

JavaScript Loops

shape Description

JavaScript Loops can execute a piece of code a number of times. JavaScript Loops are the best option when required to execute the same code repeatedly each time with a different value.

Type of Loops
In JavaScript, Loops are categorized into five types, they are:

For loop

shape Description

JavaScript Loops are used to initialize a variable, check condition and increment (or) decrement the value of a variable. All these three functions are declared in a single statement and can be executed as per the requirement.

shape Syntax

for( initialization; condition; increment/decrement)
{
statements;
}

shape Flow chart

shape Example

<!Doctype html>
<html>
	<head>
		<title>Loops</title>
			<h2 style="color: black">Example for 'for' loop</h2>
			<style>
				body{
					background-color : LightSkyBlue;
					text-shadow: 2px 2px 5px red;
					}
			</style>
	</head>
	
	<body>
 
		<script>
			var r = confirm("Press a button");
			var sum = 0;
			if(r == true)
			{
				alert("You pressed OK");
				for (var i = 1; i <= 50; i++)
				{
					sum = sum + i;
				}
			}
			else
			{
				alert("You pressed Cancel");
				alert("The sum is 0 as you have not used for loop" + sum);
			}
				 
			document.write("<h2>The sum is </h2>" +  sum );
		  
		</script>
	</body>
</html>

Output

While Loop

shape Description

While loop checks the condition until it becomes true. If the condition is false, the flow control comes out of while loop.

shape Syntax

while( condition )
{
statements;
}

shape Flowchart

shape Example

<!DOCTYPE html>
    <html>
    <body>
  
		<p>Click the button to loop through a block of code as long as i is less than 10.</p>
          
        <button onclick="splessons()">Click it</button>
          <p id="new"></p>
        <script>
            function splessons() {
                var num= "";
                var i = 0;
                //while loop iteration
                while (i < 10) {
                    num += "<br>The number is " + i;
                    i++;
                }
                document.getElementById("new").innerHTML = num;
            }
        </script>
      
    </body>
</html>

Output

Do-while loop

shape Description

Do-while loop is used when you need to execute a loop at least once irrespective of condition.

shape Syntax

do
{
Statements;
}
while( condition);

shape Flow chart

shape Example

<!DOCTYPE html>
<html>
	<head>

		<style>
			button:hover{
			 background: cyan;
			 }
		 </style>

	</head>

	<body>

	<p>Click the button to loop through a block of code as long as i value is less than 10.</p>
	<button onclick="myFunction()">Click to see the do-while output</button>
	<p id="demo"></p>
	
	<script>
		function myFunction() {
			var text = ""
			var i = 0;
			do {
				text += "<br>The number is " + i;
				i++;
			}
			while (i < 10)  
			document.getElementById("demo").innerHTML = text;
		}
	</script>

</body>
</html>

Output

for..in loop

shape Description

for…in loop performs the variable iteration and executes the statements inside the loop each time with all the object properties.

shape Syntax


for(variable in object)
{
//statements;
}

shape Examples

<!DOCTYPE html>
 	 <html>
 	 	<body>
			<p id="new"></p>
			<script>
			 var text = "";
			 var person = {fname:"Billy", lname:"John", age:23}; 
			 var a;
			 for (a in person) 
			 {
			 text += person[a] + " ";
			 }
			 document.getElementById("new").innerHTML = text;
			</script>
 	 	</body>
 	 </html>

Output

for…of loop

shape Description

for…of loop iterates on iterable objects by invoking the statements of custom iteration and executes for each distinct property value.

shape Syntax


for(variable of object)
{
//statements;
}

shape Examples

<!DOCTYPE html>
 	 <html>
 	 	<body>
			<script>
				var m = new Map();
				m.set(1, "black");
				m.set(2, "red");
				for (var n of m) {
				 console.log(n);
				 document.write("<br>",n);
				}
			</script>
 	 	</body>
 	 </html>

Output

Summary

shape Key Points

  • JavaScript Loops run a piece of code repeatedly until the condition becomes true.
  • For loop initializes variables, checks condition and performs increments/decrements of a variable value. This can be used when there is sequential input/output.
  • While loop executes after the condition becomes true.
  • Do-while loop executes at least once even if the condition is false.
  • for…in loop iterates the object properties and for…of loop iterates the object values.

shape Programming
Tips

In for loop, initialization cannot be changed once the execution goes to condition checking. So, ensure to check it before execution.