×

Html & Html5

The World's best Software Development Study Portal

Js Loops


Loops are basically used to recapitulate the piece of code . And it makes the code very compact. There are basically 4 types of Javascript :-

  • for loop
  • while loop
  • do-while loop
  • for-in loop

Js For loop

Used to recapitulate the elements for a fixed number of times.


Syntax

for (initialization; condition; increment)

{

//code to be executed

}

Let's understand this by the following example:-

<html>

<body>

<script>

      for(no=1; no<=7; n++)

     {

      document.write(no + "<br>");

}

</script>

</body>

</html>

Output of this program

1

2

3

4

5

6

7

We can see for a fixed time we recapitulate our elements here.



Js while loop

Used to recapitulate the elements for an infinite number of times.


Syntax

while (condition)

{

code execute here

}

Let's understand this by the following example:-

<html>

<body>

<script>

      var a=20;

     while(a<=25){

      document.write(a + "<br>");

      a++;

}

</script>

</body>

</html>

Output of this program

20

21

22

23

24

25



Js do while loop

It is like the while loop and here also for infinite number of times we can recapitulate the elements but here the code executed for atleast once whether the condition is true or not


Syntax

do{

     code to be executed

}

while(condition);

Let's understand this by the following example:-

<html>

<body>

<script>

      var a=10;

     do{

      document.write(a + "<br>");

      a++;

}

     while (a<=15){

</script>

</body>

</html>

Output of this program

10

11

12

13

14

15

Here we are having many possibility of many true conditions, our number can fall in any criterion. So in these type of situation we use this if... else if statement.






JS training insitute | Best IT Training classes in Gurgaon | Web Designing Training Institute