Loops
Loops allow us to automate repetition. In this section we’ll review while
, do while
, and for
loops.
Table of Contents
- Loop Da Loop - While and Do While
- Data Validation
- Loop Da Loop - For
- Loops for Arrays and Objects
- 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:
- Looping Over Array Elements with
for of
Loops - Looping Over Array Elements with
forEach
Callbacks - Looping Over an Object’s Key/Value Pairs