JavaScript Lesson 6: Loops

⚡ JavaScript CourseLesson 6 of 20 · 30% complete

JavaScript has more loop types than Python. Knowing when to use which one makes you a better developer.

for Loop

for (let i = 0; i < 5; i++) {
  console.log(i);  // 0 1 2 3 4
}

// Loop over an array
const fruits = ["apple", "banana", "cherry"];
for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

for…of — Best for Arrays

const fruits = ["apple", "banana", "cherry"];

for (const fruit of fruits) {
  console.log(fruit);
}

// With index
for (const [i, fruit] of fruits.entries()) {
  console.log(i, fruit);
}

for…in — Best for Objects

const person = { name: "Alice", age: 30, city: "London" };

for (const key in person) {
  console.log(key, ":", person[key]);
}
// name : Alice
// age : 30
// city : London

while Loop

let count = 0;
while (count < 5) {
  console.log(count);
  count++;
}

// do...while — runs at least once
let input;
do {
  input = prompt("Enter a number:");
} while (isNaN(Number(input)));

break and continue

for (let i = 0; i < 10; i++) {
  if (i === 5) break;       // stop at 5
  if (i % 2 === 0) continue; // skip even
  console.log(i);            // 1 3
}

🏋️ Practice Task

Loop from 1 to 100. Print “FizzBuzz” if divisible by both 3 and 5. Print “Fizz” for multiples of 3. Print “Buzz” for multiples of 5. Print the number otherwise. Check: 3→Fizz, 5→Buzz, 15→FizzBuzz.

💡 Hint: Use i % 3 === 0 and i % 5 === 0. Check FizzBuzz FIRST (both), then Fizz, then Buzz, then number.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *