Back

Javascript

Nested Loops

When loops are placed inside other loops, we say they are nested. Try the examples of nested loops below.

Example 1

Create a new document. Put the code below anywhere in your document. What happens? How does the script work?

<script type="text/javascript">
for( var rows = 1; rows < 30; rows++ )
{
     document.write( "<br/>" );
     for( var columns = 1; columns < 10; columns++ )
     {
          document.write( "* " );
     }
}
</script>

Example 2

Can you change the script to make the rectangle shorter? Can you make it wider? Can you make a triangle like the one below?

*
* *
* * *
* * * *
* * * * *
* * * * * *

Example 3

Erase the previous script. Then create the script below anywhere in your document. What does it do? How does it work?

<script type="text/javascript">
for( var x = 1; x < 50; x++ )
{
     for( var y = 1; y < 10; y++ )
     {
          document.write( "<br/>" );
          var product = x * y;
          for( var a = 0; a < product; a++ )
          {
               document.write( "*" );
          }
     }
}
</script>