How to Create a While Loop in JavaScript

The while JavaScript statement is an alternative to for for looping, in this case until some condition fails to be satisfied.

Things You'll Need

  • JavaScript editor
Show More

Instructions

  1. Create a While Loop in JavaScript

    • 1

      Code the while statement according to the following syntax:
      while (condition) { statement(s) }

    • 2

      Specify a condition which will eventually fail and cause the loop to be exited. For this to happen, the statements in the loop need to somehow change the condition. Here's a simple example for looping down from 4 to 1.
      var i=4;
      while (i>0) { alert (i--); }

      In this example, each iteration of the loop subtracts one frome the value of i, causing the condition i>0 to eventually fail.

    • 3

      Code a break statement to break out of the loop, regardless of the value of the condition, and continue with the statements following the loop, if necessary. Code a continue statement to stop executing further statements within the loop body and return to the top for another iteration.

Tips & Warnings

  • It's remarkably easy to code a so-called "infinite" loop, one which never terminates. Most likely, this will require exiting and restarting your web browser. Ensure that the condition in your while statement is one that will eventually fail.

Related Searches:

Comments

You May Also Like

Related Ads

Featured