Control Flow and FunctionsLesson 3.2
JavaScript Loops
for, while, do-while, for...of, for...in, break, continue
JavaScript Loops
Loops allow your JavaScript code to repeat a block of instructions multiple times. They are one of the most powerful tools in programming. Choosing the right loop for the right situation makes your code cleaner and more efficient.
The for Loop
for (let i = 0; i < 5; i++) {
console.log(`Iteration ${i}`);
}
// Prints: Iteration 0, Iteration 1, Iteration 2, Iteration 3, Iteration 4The while Loop
Use while when you do not know in advance how many times to iterate.
let attempts = 0;
while (attempts < 3) {
console.log(`Attempt ${attempts + 1}`);
attempts++;
}The do-while Loop
A do-while loop always runs the body at least once, then checks the condition.
let number;
do {
number = Math.floor(Math.random() * 10);
console.log(`Generated: ${number}`);
} while (number !== 5);
console.log('Got 5!');for...of and for...in
Use for...of to iterate over array values. Use for...in to iterate over object keys.
const fruits = ['apple', 'banana', 'cherry'];
for (const fruit of fruits) {
console.log(fruit);
}
const person = { name: 'Alice', age: 30, city: 'Paris' };
for (const key in person) {
console.log(`${key}: ${person[key]}`);
}break and continue
for (let i = 0; i < 10; i++) {
if (i === 3) continue; // skip 3
if (i === 7) break; // stop at 7
console.log(i);
}
// Prints: 0 1 2 4 5 6