Learn JavaScript
  • Introduction
  • Basics
    • Comments
    • Variables
    • Types
    • Equality
  • Numbers
    • Creation
    • Basic Operators
    • Advanced Operators
  • Strings
    • Creation
    • Concatenation
    • Length
  • Conditional Logic
    • If
    • Else
    • Comparators
    • Concatenate
  • Arrays
    • Indices
    • Length
  • Loops
    • For
    • While
    • Do...While
  • Functions
    • Declare
    • Higher order
  • Objects
    • Creation
    • Properties
    • Mutable
    • Reference
    • Prototype
    • Delete
    • Enumeration
    • Global footprint
Powered by GitBook
On this page
  1. Loops

While

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++;
}

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

PreviousForNextDo...While

Last updated 4 years ago