While Loop

Loops while a condition is true.

Examples

Basic While Loop

Looping until i equals 10.

let i = 0;
while (i < 10) {
  console.log("The number is " + i);
  i++;
}

Looping Array

Using index to loop through array.

const cars = ["BMW", "Volvo", "Saab", "Ford"];
let i = 0;
let text = "";
while (cars[i]) {
  text += cars[i] + "\n";
  i++;
}
console.log(text);

Infinite Loop Risk

Always remember to increment variables to avoid infinite loops.

let i = 0;
// if you forget i++, this loop will run forever!
/*
while (i < 10) {
    console.log(i);
}
*/

Test Your Knowledge

JavaScript Quiz

No quiz available for this topic yet.