Loops

Loops allow us to automate repetition. In this section we’ll review while, do while, and for loops.

Table of Contents

  1. Loop Da Loop - While and Do While
  2. Data Validation
  3. Loop Da Loop - For
  4. Loops for Arrays and Objects
  5. Further Reading

Loop Da Loop - While and Do While

Javascript contains standard while and do while loops. They work as you might expect:

while (booleanCondition) {
  // Loop body will execute over and over while booleanCondition remains true.
}

do {
  // Loop body executes at least once, and then repeatedly while booleanCondition remains true.
} while (booleanCondition);

Data Validation

While loops can be helpful when validating user input:

let temperature;
do {
  temperature = Number(prompt("Enter a temperature"));
} while (isNaN(temperature));

Loop Da Loop - For

Standard C-style for loops are also available. These loops are best used for counting tasks:

for (let apples = 10; apples <= 20; apples++) {
  console.log(`${apples}: How to you like them apples?`);
}

Loops for Arrays and Objects

⏳ Wait For It:

There are special loops for traversing array elements and object key/value pairs.

These are covered in the sections on Objects and Arrays:

Further Reading