GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — javascript/loops/while.md at master · begriffs/javascript

Expand file tree

/

while.md

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
62 lines (45 loc) · 1.22 KB
/

while.md

Copy path

File metadata and controls

62 lines (45 loc) · 1.22 KB
Raw
Copy raw file
Download raw file
Edit and raw actions

While Loop

While Loops repetitively execute a block of code as long as a specified condition is true.

while(condition){
    // do it as long as condition is true
}

For example, the loop in this example will repetitively execute its block of code as long as the variable i is less than 5:

var i = 0, x = "";
while (i < 5) {
    x = x + "The number is " + i;
    i++;
}

The Do/While Loop is a variant of the while loop. This loop will execute the code block once before checking if the condition is true. It then repeats the loop as long as the condition is true:

do {
    // code block to be executed
} while (condition);

Note: Be careful to avoid infinite looping if the condition is always true!


Using a while-loop, create a variable named message that equals the concatenation of integers (0, 1, 2, ...) as long as its length (message.length) is less than 100.

var message = "";
var message = "";
var i = 0;

while (message.length < 100) {
    message = message + i;
    i = i + 1;
}
var message2 = "";
var i2 = 0;

while (message2.length < 100) {
    message2 = message2 + i2;
    i2 = i2 + 1;
}
assert(message === message2);

You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.