You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Loops let you repeat a block of code multiple times without rewriting it. JavaScript provides several loop types for different situations.
The classic for loop is the most flexible. It has three parts: initialiser, condition, and update:
for (let i = 0; i < 5; i++) {
console.log("Iteration " + i);
}
// Outputs: Iteration 0, Iteration 1, Iteration 2, Iteration 3, Iteration 4
Counting backwards:
for (let i = 10; i > 0; i -= 2) {
console.log(i); // 10, 8, 6, 4, 2
}
A while loop runs as long as its condition remains true:
let count = 0;
while (count < 3) {
console.log("count is " + count);
count++;
}
Use while when you do not know in advance how many iterations you need:
let input = getUserInput();
while (input !== "quit") {
processInput(input);
input = getUserInput();
}
Be careful to always update the condition variable inside the loop, or you will create an infinite loop.
A do...while loop always executes the body at least once:
let attempts = 0;
do {
attempts++;
console.log("Attempt " + attempts);
} while (attempts < 3);
The for...of loop is the cleanest way to iterate over arrays and other iterables:
const fruits = ["apple", "banana", "cherry"];
for (const fruit of fruits) {
console.log(fruit);
}
// apple
// banana
// cherry
Arrays have a built-in forEach method that accepts a callback function:
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(function(num) {
console.log(num * 2);
});
// With an arrow function (more concise):
numbers.forEach(num => console.log(num * 2));
break exits the loop immediately. continue skips the rest of the current iteration:
// break example
for (let i = 0; i < 10; i++) {
if (i === 5) break;
console.log(i); // 0, 1, 2, 3, 4
}
// continue example
for (let i = 0; i < 6; i++) {
if (i % 2 === 0) continue; // skip even numbers
console.log(i); // 1, 3, 5
}
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.