JavaScript Loops
Repeating code execution with different loop types
🔄 What are JavaScript Loops?
Loops allow you to repeat code multiple times. Instead of writing the same code over and over, you can use loops to execute code blocks repeatedly based on conditions.
// Without loops - repetitive!
console.log("Hello 1");
console.log("Hello 2");
console.log("Hello 3");
// With loops - efficient!
for (let i = 1; i <= 3; i++) {
console.log("Hello " + i);
}
Output:
Hello 1
Hello 2
Hello 3
Types of JavaScript Loops
for Loop
Best for counting and known iterations
for (let i = 0; i < 5; i++) {
console.log(i);
}
while Loop
Repeats while condition is true
let count = 0;
while (count < 3) {
console.log(count);
count++;
}
for...in Loop
Loops through object properties
const obj = {a: 1, b: 2};
for (let key in obj) {
console.log(key);
}
for...of Loop
Loops through iterable values
const arr = [1, 2, 3];
for (let value of arr) {
console.log(value);
}
🔹 When to Use Each Loop
Choose the right loop for your specific needs:
🔸 for Loop - Use when:
- You know exactly how many times to repeat
- You need a counter variable
- Working with arrays by index
🔸 while Loop - Use when:
- You don't know how many iterations needed
- Condition might change during execution
- Reading user input until specific value
🔸 for...in Loop - Use when:
- Looping through object properties
- You need the property names/keys
🔸 for...of Loop - Use when:
- Looping through arrays, strings, or other iterables
- You need the actual values, not indexes
🔹 Loop Control Statements
Control how loops execute with break and continue:
// break - exits the loop completely
for (let i = 0; i < 10; i++) {
if (i === 5) {
break; // Stop when i equals 5
}
console.log(i); // Prints: 0, 1, 2, 3, 4
}
// continue - skips current iteration
for (let i = 0; i < 5; i++) {
if (i === 2) {
continue; // Skip when i equals 2
}
console.log(i); // Prints: 0, 1, 3, 4
}
Output:
break example:
0, 1, 2, 3, 4
continue example:
0, 1, 3, 4
🔹 Common Loop Patterns
Useful patterns you'll use frequently:
// Pattern 1: Sum numbers in array
const numbers = [1, 2, 3, 4, 5];
let sum = 0;
for (let num of numbers) {
sum += num;
}
console.log("Sum:", sum); // Sum: 15
// Pattern 2: Find maximum value
const scores = [85, 92, 78, 96, 88];
let max = scores[0];
for (let score of scores) {
if (score > max) {
max = score;
}
}
console.log("Highest score:", max); // Highest score: 96
// Pattern 3: Count occurrences
const letters = ['a', 'b', 'a', 'c', 'a'];
let count = 0;
for (let letter of letters) {
if (letter === 'a') {
count++;
}
}
console.log("Letter 'a' appears:", count, "times"); // Letter 'a' appears: 3 times