🏠
🌓
↑
🔁 JavaScript Loop Practice Exercises
Exercise 1: Print Numbers from 1 to 10 — ⭐☆☆ (Easy)
Use a for loop to print numbers from 1 to 10.
for (let i = 1; i <= 10; i++) {
console.log(i);
}
Exercise 2: Print Even Numbers from 1 to 20 — ⭐☆☆ (Easy)
Use a for loop to print even numbers from 1 to 20.
for (let i = 2; i <= 20; i += 2) {
console.log(i);
}
Exercise 3: Calculate Sum from 1 to 100 using while — ⭐⭐☆ (Medium)
Use a while loop to calculate the sum of numbers from 1 to
100.
let sum = 0, i = 1;
while (i <= 100) {
sum += i;
i++;
}
console.log(sum);
Exercise 4: Multiplication Table using do...while — ⭐⭐☆ (Medium)
Use a do...while loop to print the multiplication table of
5.
let i = 1;
const n = 5;
do {
console.log(`${n} x ${i} = ${n * i}`);
i++;
} while (i <= 10);
Exercise 5: Loop through Object using for...in — ⭐⭐☆ (Medium)
Use a for...in loop to print keys and values of an object.
const person = { name: "Ali", age: 25, city: "Colombo" };
for (let key in person) {
console.log(key + ": " + person[key]);
}
Exercise 6: Loop through Array using for...of — ⭐⭐☆ (Medium)
Use a for...of loop to print all elements of an array.
const fruits = ["apple", "banana", "mango"];
for (let fruit of fruits) {
console.log(fruit);
}
Exercise 7: Skip Odd Numbers using continue — ⭐⭐☆ (Medium)
Use a for loop and continue to skip odd
numbers.
for (let i = 1; i <= 10; i++) {
if (i % 2 !== 0) continue;
console.log(i);
}
Exercise 8: Stop Loop at First Negative using break — ⭐⭐⭐ (Hard)
Loop through an array and stop at the first negative number using
break.
const nums = [10, 15, -5, 20];
for (let num of nums) {
if (num < 0) break;
console.log(num);
}
Exercise 9: Nested Loop Pattern Printing — ⭐⭐⭐ (Hard)
Use nested for loops to print the following pattern:* ** *** **** *****
for (let i = 1; i <= 5; i++) {
let row = "";
for (let j = 1; j <= i; j++) {
row += "*";
}
console.log(row);
}
Exercise 10: FizzBuzz — ⭐⭐⭐ (Hard)
Print numbers from 1 to 50. For multiples of 3, print Fizz;
for multiples of 5, print Buzz; for both, print
FizzBuzz.
for (let i = 1; i <= 50; i++) {
if (i % 3 === 0 && i % 5 === 0) console.log("FizzBuzz");
else if (i % 3 === 0) console.log("Fizz");
else if (i % 5 === 0) console.log("Buzz");
else console.log(i);
}