JavaScript For Loop || JavaScript Loop

JavaScript

JavaScript has For Loop to perform a task in iterations. Nested loop is loop with in the loop . For each of the outer loop iteration the inner loop will complete its all iterations. The variable above the inner loop are accessible to the inner loop, So the instances of outer loop can be alter in inner loop.

For example:

  • Apply calculations in iterations like sum,average.
  • Display JavaScript alert message multiple times.etc

JavaScript for loop has three components:

  • Initialization of variable ( var x=0 ).
  • Condition for which code will executing in iterations ( x >10 ).
  • Increase in value of x with every iteration ( x++ ).

Example #1:

<!DOCTYPE html>
<html>
<body>
<p id="loop"></p>
<script>
var array=[5,5,5];
var sum=0;
for(var x=0 ; x<3 ; x++){
 sum=sum+array[i];
}
document.getElementById("loop")=innerHTML=sum
</script>
</body>
</html>

Output:

15

Using JavaScript for loop we are counting table of 2 and storing it in JavaScript array. As the following example:

Example #2:

<script> 
var table=[];
var number=2;
 for(var i=0;i<10;i++){
      table.push(number*i)
}
 console.log(table);

</script>

Output:

(10) [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

Nested for loop:

Nested loop is loop with in the loop . For each of the outer loop iteration the inner loop will complete its all iterations. The variable above the inner loop are accessible to the inner loop, So the instances of outer loop can be alter in inner loop.

Example #3:

We will calculate tables from 0 to 10 in nested loop:

<script> 
tables=[]
 for(var i=0;i<=10;i++){
    tables.push([])
    for(var j=0;j<=10;j++){
        tables[i].push(i*j);
    }

}
 console.log(tables);

</script>

Output:

(11) [Array(11), Array(11), Array(11), Array(11), Array(11), Array(11), Array(11), Array(11), Array(11), Array(11), Array(11)]
0: (11) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
1: (11) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
2: (11) [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
3: (11) [0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30]
4: (11) [0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40]
5: (11) [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
6: (11) [0, 6, 12, 18, 24, 30, 36, 42, 48, 54, 60]
7: (11) [0, 7, 14, 21, 28, 35, 42, 49, 56, 63, 70]
8: (11) [0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80]
9: (11) [0, 9, 18, 27, 36, 45, 54, 63, 72, 81, 90]
10: (11) [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
length: 11 

For more Examples Related CSS,html and Java Script Visit on Coding Academics

Leave a Reply

Your email address will not be published. Required fields are marked *