JavaScript Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 2.00

"for" Loop Statement Example

This section provides a JavaScript tutorial example showing how to write a 'for' loop statement.

To help you understand how "for" loop statements work, I wrote the following the JavaScript tutorial example, For_Loop_Statements.html:

<html>
<!-- For_Loop_Statements.html
   Copyright (c) 2008 by Dr. Herong Yang, http://www.herongyang.com/
-->
<head><title>For Loop Statements</title></head>
<body>
<pre>
<script type="text/javascript">
   var i, j, is_prime;
   for ( i=3; i<=30; i+=2 ) {
      is_prime = true;
      for ( j=2; j<=i/2; j++) {
         is_prime = i%j > 0;
         if (!is_prime) break;
      }
      if (is_prime)
         document.write("Found a prime number: " + i + ".\n");
   }
</script>
</pre>
</body>
</html>

Note that:

  • This JavaScript uses a nested "for" loop statements to calculate prime numbers.
  • The outer "for" loop uses variable "i" to control the loop execution.
  • The inner "for" loop uses variable "j" to control the loop execution.
  • The outer "for" loop's stop condition is "i<=30". The value of "i" is increased by 2 in each iteration.
  • The inner "for" loop's stop condition is "j<=i/2". The value of "j" is increased by 1 in each iteration.
  • The inner "for" loop has a "break" statement that will break the loop when "is_prime" is true.

The output of this sample JavaScript is:

Found a prime number: 3.
Found a prime number: 5.
Found a prime number: 7.
Found a prime number: 11.
Found a prime number: 13.
Found a prime number: 17.
Found a prime number: 19.
Found a prime number: 23.
Found a prime number: 29.

Sections in This Chapter

What Is a Statement?

Conditional "if" Statements

Conditional "if" Statement Examples

"switch ... case" Statements

"switch ... case" Statement Example

"for" Loop Statements

"for" Loop Statement Example

"while" Loop Statements

"while" Loop Statement Example

Dr. Herong Yang, updated in 2008
"for" Loop Statement Example