Loops
Loops execute a block of code multiple times. JavaScript has several types of loops:
for Loop:
Best when you know how many iterations you need.
for (initialization; condition; increment) { }
while Loop: Runs while a condition is true. Check happens before each iteration.
do...while Loop: Like while, but runs at least once (check after iteration).
for...of Loop: Iterates over iterable objects (arrays, strings, etc.). Gets values.
for...in Loop: Iterates over object properties. Gets keys.
Loop Control:
- break: Exit the loop entirely
- continue: Skip to the next iteration
Best Practices:
- Use for...of for arrays (cleaner syntax)
- Avoid for...in for arrays (use for objects)
- Be careful with infinite loops
- Use descriptive variable names in loops
Code Examples
// Basic for loop
console.log("Counting to 5:");
for (let i = 1; i <= 5; i++) {
console.log(i);
}
// Looping through array with for
let colors = ["red", "green", "blue"];
console.log("\nColors with index:");
for (let i = 0; i < colors.length; i++) {
console.log(i + ": " + colors[i]);
}
// for...of loop (preferred for arrays)
console.log("\nColors with for...of:");
for (let color of colors) {
console.log(color);
}
// for...in loop (for objects)
let person = { name: "Alice", age: 30, city: "NYC" };
console.log("\nPerson properties:");
for (let key in person) {
console.log(key + ": " + person[key]);
}
// Nested loops
console.log("\nMultiplication table (1-3):");
for (let i = 1; i <= 3; i++) {
let row = "";
for (let j = 1; j <= 3; j++) {
row += (i * j) + "\t";
}
console.log(row);
}Use for...of for arrays and for...in for objects. The traditional for loop is best when you need the index.
// while loop - check before iteration
let count = 0;
console.log("While loop:");
while (count < 3) {
console.log("Count: " + count);
count++;
}
// do...while - runs at least once
let num = 10;
console.log("\nDo-while with num = 10:");
do {
console.log("This runs at least once! num = " + num);
num++;
} while (num < 5); // condition is false!
// break - exit loop early
console.log("\nSearching for 'green':");
let items = ["red", "green", "blue"];
for (let item of items) {
if (item === "green") {
console.log("Found green!");
break; // stop searching
}
console.log("Checked: " + item);
}
// continue - skip iteration
console.log("\nOdd numbers only:");
for (let i = 1; i <= 5; i++) {
if (i % 2 === 0) {
continue; // skip even numbers
}
console.log(i);
}Use break to exit a loop early and continue to skip the current iteration. Be careful with while loops to avoid infinite loops!
Quick Quiz
1. Which loop is guaranteed to run at least once?
2. Which loop type is best for iterating over array values?
Was this lesson helpful?