"while" Loop Statement Example

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

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

<html>
<!-- While_Loop_Statements.html
   Copyright (c) 2002 HerongYang.com. All Rights Reserved.
-->
<head><title>While Loop Statements</title></head>
<body>
<pre>
<script type="text/javascript">
   var i, j, is_prime;
   i = 3;
   while ( i<=30 ) {
      is_prime = true;
      j = 2;
      while ( j<=i/2 ) {
         is_prime = i%j > 0;
         if (!is_prime) break;
         j++;
      }
      if (is_prime)
         document.write("Found a prime number: " + i + ".\n");
      i += 2;
   }
</script>
</pre>
</body>
</html>

This JavaScript uses a nested "while" loop statements to calculate prime numbers. It has the same execution logic as the While_Loop_Statements.html JavaScript.

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.

Table of Contents

 About This Book

 Introduction to JavaScript

 ECMAScript Language Specification and JavaScript Dialects

 Data Types, Variables and Expressions

Flow Control Statements

 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

 Creating, Accessing, and Manipulating Arrays

 Defining and Calling Functions

 Web Browser Supporting JavaScript

 Server-Side and Client-Side Web Scripting

 Introduction to Objects

 Defining Your Own Object Types

 Inheritance of Properties and Methods through the Prototype Object Chain

 'jrunscript' - JavaScript Shell Command from JDK

 Using Functions as "Function" Objects

 Introduction to Built-in Object Types

 W3C's Document Object Model (DOM) Specifications

 AJAX (Asynchronous JavaScript And XML)

 References

 Full Version in PDF/EPUB