What is Nested For loop in JavaScript ?
Simply nested means block within block.So, Nested For loop is a For loop inside another For loop.
Syntax of Nested For loop
for(initialization;condition;increment/decrement) { for(initialization;condition;increment/decrement) { //statements. } //end of inner loop } //end of outer loop
Example of Nested For loop:
<html>
<head>
<title>Nested for loop</title>
</head>
<body>
<script>
var i,j;
for(i=1;i<=3;i++)
{
for(j=1;j<=3;j++)
{
document.write(j);
}//end of inner loop
document.write("<br>");
}//end of outer loop
</script>
</body>
</html>
<head>
<title>Nested for loop</title>
</head>
<body>
<script>
var i,j;
for(i=1;i<=3;i++)
{
for(j=1;j<=3;j++)
{
document.write(j);
}//end of inner loop
document.write("<br>");
}//end of outer loop
</script>
</body>
</html>
Output:
123
123
123
123
123
In the above example,you can see that the pattern 123 will we printed in 3 rows and 3 columns format.Rows will be printed by the outer loop and columns will be printed by inner loop.