Header Ads Widget

JavaScript loops

In previous posts, we had seen about two conditional statements if and switch. Both are used to decide which block of code to be executed. But when you want to execute the same code multiple times the loops are used for that.

This post will explain to you about loops in JavaScript.

What are the loops in JavaScript?

Loops execute the same code block multiple times until the condition becomes false.

Suppose you want to print “javascript” 10 times. Instead of writing 10 times use the loop and set logical expression (less than or equal to 10) so that will display “hello word” 10 times in output.

How many types of loops are there in JavaScript?

There are 5 types of loops in JavaScript.

1. while loop

2. do while loop

3. for loop

4. for/in loop

5. for/of loop

while loop

The while loop first evaluates the condition, if it evaluates true then the code block after the conditional statement will be executed. The iteration of the loop continued until the condition becomes false.

If the condition is evaluated as false at first execution then the code block will not be executed.

Syntax of while loop

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

Example of while loop

An example display odd numbers between 1 to 20.

<!DOCTYPE html>
<html>
<head>
<title>while loop</title>
</head>
<body>
<h2>while loop</h2>
<h3>Odd numbers between 1 to 20</h3>
<script>
let a=1;
while(a<20)
{
document.write(a,"&nbsp;&nbsp;");//&nbsp; for space
a++;
a++;
}
</script>
</body>
</html>

The value of variable 'a' is 1. When program execution starts condition is evaluated, if it is true (1<20) then variable value 1 is printed. After that variable ‘a’ increments 2 times using the increment operator (++). Now the value of ‘a’ is 3 which is less than 20, condition again true and 3 is printed. The iteration of the loop continued until the value of ‘a’ is greater than 20. When a=21, a is greater than 20, the condition is evaluated false and execution stops.

Output:-
Javascript while loop
while loop example


do while loop

The do while loop first executes the code block then evaluates the condition and the loop continued its iteration until the condition becomes false.
In do while loop, the code block will execute at least once.

Syntax of do while loop

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

Example of do while loop

Display odd numbers between 1 to 20 using do while loop.


<!DOCTYPE html>
<html>
<head>
<title>do while loop</title>
</head>
<body>
<h2>do while loop</h2>
<h3>Odd numbers between 1 to 20</h3>
<script>
var a=1;
do
{
a++;
a++;
document.write(a,"&nbsp;&nbsp;");
}while(a<20);
</script>
</body>
</html>

The value of variable 'a' is 1. Variable ‘a’ increments two times now the value is 3 displayed on the output screen. After that ‘while’ condition (3<20) is evaluated to be true and the loop will continue its execution. The execution has repeated until the condition becomes false (21<20).

Output:-

do while loop example


Output 21 is also displayed because here condition is evaluated later and the code block is executed first.

Difference between while and do while loops

   while loop

  • condition evaluated first, then after code block will be executed if a condition is true.
  • If the condition becomes false at the first evaluation, the code block will not be executed.

   do while loop

  • The code block will be executed first, then the condition will be evaluated.
  •  The code block will be executed minimum one time even after the condition becomes false.

for loop

for loop executes the code block until a condition becomes false. for loop have three parts: initialization part, condition part, and increment/decrement part.

Initialization part

The initialization part includes the declaration/initialization of the variable. It is optional to declare variables inside for loop if it is declared outside the loop, otherwise error occurs.

Condition part

The condition part decides how many times the loop will be executed. If you omit the condition part the loop will be executed infinitely.

Increment/Decrement part

The last part is the increment /decrement part which includes increment or decrement of variable value. If this part is omitted loop will execute infinitely.

Syntax of for loop

for(initialization part; condition part; increment/decrement part)
{
// code block to be executed
}


Example of for loop

The following example displays even numbers between 1 to 20.

<!DOCTYPE html>
<html>
<head>
<title>for loop</title>
</head>
<body>
<h2>for loop</h2>
<h3>Even numbers between 1 to 20 using for loop</h3>
<script>
for(i=2;i<=20;i+=2)
{
document.write(i,"&nbsp;&nbsp;");
}
</script>
</body>
</html>

The condition expression (2<=20) is evaluated, if a condition is true, 2 is printed in output. Now the variable value is incremented two times using addition assignment operator. Now the variable value is 4, again condition checked. The loop continues its execution until the variable value reaches 22. When the variable value becomes 22, it is greater than 20, and the condition expression becomes false, execution will stop.

Output:-


JavaScript for loop
for loop example

Display multiplication table using for loop 

This is a tiny mini project that displays a multiplication table of entered numbers by the user.

One input field and two buttons have been taken. 
The function table () and clear() function called on buttons to display and remove the table.

HTML

<!Doctype html>
<head>
<title>Multiplication table</title>
</head>
<body>
<h2>Multiplication Table</h2>
<input type="number" id="num" placeholder="Enter digit">
<button onclick="table()">Display table</button>
<button onclick="del()">clear</button>
<p id="tableview"></p>
</body>
</html>

CSS

body{
background-color:#181818;
}
h2,p,button{
color:#d6d6d6;
}
input{
width:100px;
height:30px;
}
input:hover{
box-shadow:3px 3px 15px #f3f3f3;
}
button{
width:30%;
height:35px;
border:3px groove #b0802a;
border-radius:5px;
background-color:#d4622b;
box-shadow:3px 3px 15px #d4622b;
}
button:hover{
border:3px inset #b0802a;
}

JavaScript

      function table()
      {
      var n=document.getElementById("num").value;
       if(n=="")
       {
       document.getElementById("tableview").innerHTML="please enter digit";
       }
       else
       {
       for(i=1;i<=10;i++)
       {
       var result=document.getElementById("tableview");
       result.innerHTML+=(n+"*"+i+"="+n*i)+"</br>";
       }
       }
      }
      function del()
      {
      var del=document.getElementById("tableview");
      del.innerHTML="";
      }

Output:-


for/ in loop

The for/in loop is iterated by the property or key of an object. It is used for objects or arrays.

Syntax of for/in loop

for( key in object)
{
//JavaScript statement
}

Explanation
A key is one kind of variable declared in for/in          loop.
A key represents the properties of an object.
An object contains the name of an object that should define before for/in loop.
The for…in loop iterate over an object and display its properties' values in the output.

Example of for/in loop

fruit object is defined by name, color, type, and flavor properties. The key 'f' in for…in loop is used to access fruit property. The value of the property is accessed by object_name[key]. For example fruit[f].

<!DOCTYPE html>
<html>
<head>
<title>for...in loop</title>
</head>
<body>
<h2>for...in loop</h2>
<h3>description about your favorite fruit</h3>
<script>
const fruit={
name:"mango",
color:"yellow",
type:"kesar",
flavor:"sweet"};
for(let f in fruit)
{
document.write(fruit[f],"<br>");
}
</script>
</body>
</html>

Output:-
JavaScript for/in loop
for...in loop example

An array of values can also be accessed like an object.

for/of loop

The for/of loop iterates over the object property. It is a loop over an array, list, map, and more. for…of introduced in 2015 by ES6.

Syntax of for/of loop


for(variable of object)
{
//JavaScript statement
}

Explanation

The object can be an array, string, etc... The new value is assigned to a variable on each iteration of an object.

Example 1

for…of loop is iterating over variable designation which has value in a string. On each iteration, a single character is assigned to variable d.


<!DOCTYPE html>
<html>
<head>
<title>for...of loop</title>
<h2>for...of loop</h2>
</head>
<body>
<script>
//looping over string
let designation="web devloper";
for(let d of designation)
{
document.write(d);
}
</script>
</body>
</html>

Output:-
JavaScript for...of loop
for/of loop example

Example 2
for…of loop is iterating over fruit array. On each iteration, a new value of the fruit array is assigned to variable f.


<!DOCTYPE html>
<html>
<head>
<title>for...of loop</title>
</head>
<body>
<script>
//looping over array
let fruit=["Apple","Banana","Mango"];
for(let f of fruit)
{
document.write(f,"<br>");
}
</script>
</body>
</html>

Output:-
JavaScript for/of loop
for/of loop example

Summary

This post has covered 5 loops used in JavaScript. The while and do while loops are control flow statements. The for loops are iterable statements. Omitting condition expression may occur errors in while and do while loops but in for loop condition expression is optional, but without it, the loop will execute infinitely.

Post a Comment

0 Comments