JavaScript Loop Fundamentals

Loops allow you to execute code repeatedly based on a condition.


1️⃣ Basic for Loop

👉 Example:

for (let i = 1; i <= 5; i++) {
console.log(i);
}

💡 Output:

1 2 3 4 5

2️⃣ Loop with if Condition

👉 Example: Print even numbers

for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) {
console.log(i);
}
}

💡 Output:

2 4 6 8 10

3️⃣ Nested for Loop

👉 Example: Pattern (matrix)

for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
console.log(`Row ${i}, Column ${j}`);
}
}

💡 Concept:

  • Outer loop → rows
  • Inner loop → columns

4️⃣ while Loop

👉 Example:

let i = 1;while (i <= 5) {
console.log(i);
i++;
}

💡 Use case:

  • When iteration count is unknown

5️⃣ do...while Loop

👉 Example:

let i = 1;do {
console.log(i);
i++;
} while (i <= 5);

💡 Key Point:

  • Executes at least once

6️⃣ forEach Loop (Array Only)

👉 Example:

let arr = [10, 20, 30];arr.forEach((value, index) => {
console.log(index, value);
});

7️⃣ Loop with String Datatype

A string is iterable, so you can loop through characters.

👉 Example using for

let str = "Hello";for (let i = 0; i < str.length; i++) {
console.log(str[i]);
}

👉 Example using for...of

for (let char of "Hello") {
console.log(char);
}

💡 Output:

H e l l o

8️⃣ Loop with Array Datatype

👉 Example using for

let numbers = [1, 2, 3, 4];for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}

👉 Example using for...of

for (let num of numbers) {
console.log(num);
}

👉 Example using forEach

numbers.forEach(num => console.log(num));

9️⃣ Loop with Object Datatype

Objects are not directly iterable like arrays, but we use for...in.

👉 Example:

let person = {
name: "John",
age: 25,
city: "Delhi"
};for (let key in person) {
console.log(key, person[key]);
}

💡 Output:

name John
age 25
city Delhi

🔥 Summary Table

Loop TypeBest Use Case
forFixed iterations
whileUnknown iterations
do...whileRuns at least once
forEachArrays
for...ofArrays & strings
for...inObjects

Common Mistakes

❌ Infinite Loop

for (let i = 1; i <= 5; ) {
// missing increment
}

❌ Wrong Object Loop

for (let item of person) // ❌ Error

✔ Correct:

for (let key in person)

✅ Practice Ideas

  1. Reverse a string using loop
  2. Find largest number in array
  3. Count vowels in string
  4. Print object keys and values
  5. Create star pattern using nested loop

Leave a Comment