Chapter 6 Beginner 60 Questions

Practice Questions — Loops (for, while, for...of, for...in)

← Back to Notes
11 Easy
12 Medium
10 Hard

Topic-Specific Questions

Question 1
Easy
What is the output of the following code?
for (let i = 0; i < 4; i++) {
  console.log(i);
}
The loop starts at 0 and runs while i is less than 4.
0
1
2
3
Question 2
Easy
What is the output?
for (let i = 1; i <= 5; i++) {
  console.log(i * 2);
}
Multiply each value of i by 2.
2
4
6
8
10
Question 3
Easy
What is the output?
const fruits = ["apple", "mango", "banana"];
for (const fruit of fruits) {
  console.log(fruit);
}
for...of gives you each value in the array.
apple
mango
banana
Question 4
Easy
What is the output?
let count = 3;
while (count > 0) {
  console.log(count);
  count--;
}
count starts at 3 and decreases by 1 each time.
3
2
1
Question 5
Easy
What is the output?
for (const char of "Hi!") {
  console.log(char);
}
for...of on a string gives you each character.
H
i
!
Question 6
Easy
What is the output?
for (let i = 10; i >= 6; i--) {
  console.log(i);
}
The loop counts down from 10, stopping when i goes below 6.
10
9
8
7
6
Question 7
Medium
What is the output?
for (let i = 1; i <= 5; i++) {
  if (i === 3) continue;
  console.log(i);
}
continue skips the rest of the current iteration.
1
2
4
5
Question 8
Medium
What is the output?
for (let i = 1; i <= 10; i++) {
  if (i === 4) break;
  console.log(i);
}
break exits the loop entirely.
1
2
3
Question 9
Medium
What is the output?
let x = 1;
while (x < 20) {
  x *= 2;
}
console.log(x);
Trace x: 1, 2, 4, 8, 16, ... When does x first reach 20 or more?
32
Question 10
Medium
What is the output?
let num = 10;
do {
  console.log(num);
  num += 10;
} while (num < 5);
do...while always runs the body at least once before checking the condition.
10
Question 11
Medium
What is the output?
const obj = { a: 1, b: 2, c: 3 };
for (const key in obj) {
  console.log(key);
}
for...in gives you the property names (keys), not the values.
a
b
c
Question 12
Medium
What is the output?
let total = 0;
for (let i = 1; i <= 5; i++) {
  total += i;
}
console.log(total);
Add 1 + 2 + 3 + 4 + 5.
15
Question 13
Hard
What is the output?
for (let i = 1; i <= 3; i++) {
  for (let j = 1; j <= 2; j++) {
    console.log(i + "," + j);
  }
}
The inner loop runs completely (j=1, j=2) for each value of i.
1,1
1,2
2,1
2,2
3,1
3,2
Question 14
Hard
What is the output?
for (let i = 0; i < 3; i++) {
  for (let j = 0; j <= i; j++) {
    process.stdout.write("* ");
  }
  console.log();
}
The inner loop runs i+1 times for each row.
*
* *
* * *
Question 15
Hard
What is the output?
const arr = [10, 20, 30, 40];
let result = 0;
for (const val of arr) {
  if (val === 30) break;
  result += val;
}
console.log(result);
The loop adds values until it hits 30, then breaks.
30
Question 16
Hard
What is the output?
let count = 0;
for (let i = 0; i < 4; i++) {
  for (let j = 0; j < 4; j++) {
    if (i === j) count++;
  }
}
console.log(count);
How many times does i equal j in a 4x4 grid?
4
Question 17
Medium
What is the difference between for...of and for...in? When should you use each one?
Think about what each loop gives you: values vs keys.
for...of iterates over values of iterable objects like arrays and strings. for...in iterates over property names (keys) of objects. Use for...of for arrays and strings. Use for...in for plain objects. Never use for...in on arrays because it gives string indices and can include inherited properties.
Question 18
Easy
What is the difference between break and continue?
One stops the loop entirely, the other skips one iteration.
break exits the loop completely - no more iterations run. continue skips the rest of the current iteration and moves on to the next one. With break, the loop is done. With continue, the loop keeps going.
Question 19
Hard
What is the output?
const word = "JavaScript";
let vowels = 0;
for (const ch of word) {
  if ("aeiouAEIOU".includes(ch)) {
    vowels++;
  }
}
console.log(vowels);
Count the vowels in "JavaScript": J-a-v-a-S-c-r-i-p-t.
3
Question 20
Easy
What is the output?
for (let i = 0; i < 3; i++) {
  console.log("Hello");
}
How many times does the loop run? i goes 0, 1, 2.
Hello
Hello
Hello

Mixed & Application Questions

Question 1
Easy
What is the output?
const nums = [5, 10, 15];
for (const n of nums) {
  console.log(n + 1);
}
Add 1 to each element.
6
11
16
Question 2
Easy
What is the output?
let sum = 0;
for (let i = 2; i <= 10; i += 2) {
  sum += i;
}
console.log(sum);
i takes values 2, 4, 6, 8, 10. Add them up.
30
Question 3
Medium
What is the output?
for (let i = 1; i <= 5; i++) {
  if (i % 2 === 0) continue;
  console.log(i);
}
continue skips even numbers.
1
3
5
Question 4
Medium
What is the output?
const scores = { maths: 95, science: 88, english: 76 };
for (const subject in scores) {
  if (scores[subject] >= 90) {
    console.log(subject);
  }
}
Only print subjects where the score is 90 or above.
maths
Question 5
Medium
What is the output?
let result = "";
for (let i = 3; i >= 1; i--) {
  for (let j = 1; j <= i; j++) {
    result += "*";
  }
  result += "\n";
}
console.log(result);
The inner loop runs i times. i goes 3, 2, 1.
***
**
*
Question 6
Medium
What is the output?
let i = 5;
while (i > 0) {
  i -= 2;
}
console.log(i);
Trace: 5, 3, 1, -1. What stops the loop?
-1
Question 7
Hard
What is the output?
const matrix = [[1, 2], [3, 4], [5, 6]];
for (const row of matrix) {
  for (const val of row) {
    console.log(val);
  }
}
The outer loop gets each sub-array. The inner loop gets each value within that sub-array.
1
2
3
4
5
6
Question 8
Hard
What is the output?
let n = 1;
for (let i = 0; i < 4; i++) {
  n *= 3;
}
console.log(n);
Multiply n by 3 four times: 1 * 3 * 3 * 3 * 3.
81
Question 9
Hard
What is the output?
const text = "hello";
let reversed = "";
for (let i = text.length - 1; i >= 0; i--) {
  reversed += text[i];
}
console.log(reversed);
Start from the last character and go backwards.
olleh
Question 10
Hard
What is the output?
outer:
for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    if (j === 1) continue outer;
    console.log(i, j);
  }
}
continue outer skips to the next iteration of the outer loop, not the inner one.
0 0
1 0
2 0
Question 11
Medium
Why should you use let instead of var in a for loop? What problem does var cause?
Think about variable scope and closures.
var is function-scoped, meaning there is only one variable shared across all iterations. let is block-scoped, creating a new variable for each iteration. With var, if you use the loop variable inside a callback (like setTimeout), all callbacks will see the final value of the variable. With let, each callback captures its own copy of the variable.
Question 12
Easy
What is the output?
for (let i = 0; i < 5; i += 2) {
  console.log(i);
}
i starts at 0 and increases by 2 each time.
0
2
4
Question 13
Hard
What is the output?
let a = 0;
let b = 1;
for (let i = 0; i < 7; i++) {
  let temp = a + b;
  a = b;
  b = temp;
}
console.log(a);
This generates Fibonacci numbers. Trace a few iterations.
13

Multiple Choice Questions

MCQ 1
What are the three parts of a for loop in JavaScript?
  • A. start, end, step
  • B. initialization, condition, update
  • C. begin, check, increment
  • D. declare, test, change
Answer: B
B is correct. A for loop has three parts separated by semicolons: initialization (runs once), condition (checked before each iteration), and update (runs after each iteration). The other options use informal terms that are not standard.
MCQ 2
Which loop always runs its body at least once?
  • A. for loop
  • B. while loop
  • C. do...while loop
  • D. for...of loop
Answer: C
C is correct. The do...while loop executes the body first and then checks the condition. This guarantees at least one execution. The other loops check the condition before running the body, so they might not run at all.
MCQ 3
Which loop is best for iterating over array values?
  • A. for...in
  • B. for...of
  • C. while
  • D. do...while
Answer: B
B is correct. for...of is designed to iterate over values of iterable objects like arrays and strings. for...in (option A) iterates over keys and should not be used on arrays. while and do...while work but require manual index management.
MCQ 4
What does the break statement do inside a loop?
  • A. Skips the current iteration
  • B. Restarts the loop
  • C. Exits the loop immediately
  • D. Pauses the loop
Answer: C
C is correct. break exits the loop completely, stopping all further iterations. Option A describes continue. Options B and D are not real loop behaviors in JavaScript.
MCQ 5
How many times does this loop run? for (let i = 0; i < 6; i++)
  • A. 5 times
  • B. 6 times
  • C. 7 times
  • D. Infinite times
Answer: B
B is correct. The loop starts at i=0 and runs while i < 6. The values of i are 0, 1, 2, 3, 4, 5 - that is 6 iterations. When i becomes 6, the condition fails and the loop stops.
MCQ 6
What does for...in loop over?
  • A. Array values
  • B. Object property names (keys)
  • C. String characters
  • D. Number sequences
Answer: B
B is correct. for...in iterates over the enumerable property names (keys) of an object. While it technically works on arrays (giving string indices), it is designed for objects. Use for...of for array values and string characters.
MCQ 7
What is the output of: let i = 10; while (i < 5) { console.log(i); i++; }
  • A. 10
  • B. 5 6 7 8 9
  • C. Nothing is printed
  • D. Infinite loop
Answer: C
C is correct. The while loop checks the condition before running the body. Since 10 < 5 is false from the start, the body never executes. Nothing is printed.
MCQ 8
What causes an infinite loop?
  • A. Using too many variables
  • B. The loop condition never becoming false
  • C. Using nested loops
  • D. Using break inside a loop
Answer: B
B is correct. An infinite loop occurs when the condition never becomes false, usually because the loop variable is not updated correctly. Nested loops (C) and multiple variables (A) are perfectly fine. break (D) actually stops a loop.
MCQ 9
What is the difference between continue and break?
  • A. continue exits the loop, break skips an iteration
  • B. continue skips the current iteration, break exits the loop
  • C. They do the same thing
  • D. continue works in for loops only, break works in while loops only
Answer: B
B is correct. continue skips the rest of the current iteration and goes to the next one. break exits the loop entirely. Both work in all loop types (for, while, do...while, for...of, for...in).
MCQ 10
Which loop type should you NOT use with arrays?
  • A. for loop
  • B. for...of loop
  • C. for...in loop
  • D. while loop
Answer: C
C is correct. for...in should not be used with arrays because it iterates over indices as strings and can include inherited properties. Use a regular for loop or for...of for arrays.
MCQ 11
How many times does the inner console.log execute?
for (let i = 0; i < 5; i++) {
  for (let j = 0; j < 3; j++) {
    console.log(i, j);
  }
}
  • A. 5
  • B. 3
  • C. 8
  • D. 15
Answer: D
D is correct. The outer loop runs 5 times and the inner loop runs 3 times for each outer iteration. Total: 5 x 3 = 15. Option C (8) incorrectly adds instead of multiplying.
MCQ 12
What is the output?
for (let i = 0; i < 3; i++) {
  // empty body
}
console.log(typeof i);
  • A. "number"
  • B. "undefined"
  • C. 3
  • D. ReferenceError
Answer: D
D is correct. When you use let in a for loop, the variable is scoped to the loop block. After the loop ends, i does not exist in the outer scope. Trying to access it throws a ReferenceError. This is different from var, which would make i accessible.
MCQ 13
What does the following code create on a webpage?
const items = ["A", "B", "C"];
const ul = document.createElement("ul");
for (const item of items) {
  const li = document.createElement("li");
  li.textContent = item;
  ul.appendChild(li);
}
  • A. A table with 3 rows
  • B. An unordered list with 3 items
  • C. 3 separate paragraphs
  • D. 3 div elements
Answer: B
B is correct. The code creates a <ul> element and loops through the array, creating a <li> for each item and appending it to the ul. The result is an unordered list with 3 list items: A, B, C.
MCQ 14
What is a labeled statement used for with loops?
  • A. Adding comments to loops
  • B. Naming loops so break/continue can target a specific outer loop
  • C. Making loops run faster
  • D. Creating loop variables
Answer: B
B is correct. Labels like outer: allow break outer or continue outer to affect the labeled loop instead of just the innermost loop. This is useful in nested loops when you want to break out of or continue an outer loop from inside an inner loop.
MCQ 15
What does continue do?
  • A. Stops the loop entirely
  • B. Restarts the loop from the beginning
  • C. Skips the rest of the current iteration and goes to the next
  • D. Pauses the loop for 1 second
Answer: C
C is correct. continue skips the remaining code in the current iteration and immediately starts the next iteration (after running the update expression in a for loop). It does not stop the loop or restart it.
MCQ 16
What is the correct syntax for a do...while loop?
  • A. do { } while (condition)
  • B. do (condition) { }
  • C. while (condition) do { }
  • D. do { } (condition)
Answer: A
A is correct. The syntax is do { body } while (condition);. The body comes first, then the while keyword with the condition. Note the semicolon after the closing parenthesis.
MCQ 17
What happens when you use for...of on a regular object?
  • A. It loops over the values
  • B. It loops over the keys
  • C. It throws a TypeError
  • D. It returns undefined
Answer: C
C is correct. Regular objects are not iterable, so for...of throws a TypeError saying the object is not iterable. Use for...in for object keys, or convert with Object.keys()/Object.values() to make an iterable array.

Coding Challenges

Challenge 1: Sum of Odd Numbers

Easy
Write a program that uses a for loop to calculate and print the sum of all odd numbers from 1 to 25.
Sample Input
(No input required)
Sample Output
Sum of odd numbers from 1 to 25: 169
Use a for loop. Do not hardcode the answer.
let sum = 0;
for (let i = 1; i <= 25; i += 2) {
  sum += i;
}
console.log("Sum of odd numbers from 1 to 25:", sum);

Challenge 2: Reverse a String Using a Loop

Easy
Aarav has the string "JavaScript". Write a program using a for loop to print the string in reverse order.
Sample Input
(No input required)
Sample Output
tpircSavaJ
Use a for loop counting backwards. Do not use built-in reverse methods.
const text = "JavaScript";
let reversed = "";
for (let i = text.length - 1; i >= 0; i--) {
  reversed += text[i];
}
console.log(reversed);

Challenge 3: Create 10 Div Elements with Different Colors

Easy
Write a loop that creates 10 div elements. Each div should have a different background color from this array: ["red", "orange", "yellow", "green", "teal", "blue", "indigo", "purple", "pink", "brown"]. Set each div's width to 100px, height to 50px, and display the color name as text.
Sample Input
(No input required)
Sample Output
(10 colored divs appear on the webpage, each showing its color name)
Use a for loop to create elements. Do not write the HTML manually.
const colors = ["red", "orange", "yellow", "green", "teal", "blue", "indigo", "purple", "pink", "brown"];

for (let i = 0; i < colors.length; i++) {
  const div = document.createElement("div");
  div.textContent = colors[i];
  div.style.backgroundColor = colors[i];
  div.style.color = "white";
  div.style.width = "100px";
  div.style.height = "50px";
  div.style.display = "flex";
  div.style.alignItems = "center";
  div.style.justifyContent = "center";
  div.style.margin = "4px";
  document.body.appendChild(div);
}

Challenge 4: FizzBuzz

Medium
Priya is practicing a classic programming challenge. Write a program that prints numbers 1 to 30. For multiples of 3, print "Fizz". For multiples of 5, print "Buzz". For multiples of both 3 and 5, print "FizzBuzz".
Sample Input
(No input required)
Sample Output
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz ...
Use a for loop. Check for both 3 and 5 first.
for (let i = 1; i <= 30; 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);
  }
}

Challenge 5: Multiplication Table on a Webpage

Medium
Rohan wants to display a 10x10 multiplication table on a webpage using nested loops. Create an HTML table where each cell shows the product of its row and column numbers.
Sample Input
(No input required)
Sample Output
(A 10x10 HTML table showing products: 1, 2, 3... in row 1; 2, 4, 6... in row 2; etc.)
Use nested for loops. Create table, tr, and td elements with JavaScript.
const table = document.createElement("table");
table.style.borderCollapse = "collapse";

for (let i = 1; i <= 10; i++) {
  const tr = document.createElement("tr");
  for (let j = 1; j <= 10; j++) {
    const td = document.createElement("td");
    td.textContent = i * j;
    td.style.border = "1px solid #555";
    td.style.padding = "8px";
    td.style.textAlign = "center";
    tr.appendChild(td);
  }
  table.appendChild(tr);
}

document.body.appendChild(table);

Challenge 6: Count Vowels in a String

Medium
Ananya has the string "Modern Age Coders teaches JavaScript". Write a program using for...of to count the number of vowels (a, e, i, o, u - both cases).
Sample Input
(No input required)
Sample Output
Vowels: 12
Use a for...of loop to iterate through the string.
const text = "Modern Age Coders teaches JavaScript";
let count = 0;
for (const ch of text) {
  if ("aeiouAEIOU".includes(ch)) {
    count++;
  }
}
console.log("Vowels:", count);

Challenge 7: Build a Student List from an Array of Objects

Medium
Kavya has an array of student objects: [{name: "Aarav", grade: "10th"}, {name: "Diya", grade: "9th"}, {name: "Vikram", grade: "11th"}, {name: "Meera", grade: "10th"}]. Use a for...of loop to create an unordered list on the webpage where each item shows "Name - Grade".
Sample Input
(No input required)
Sample Output
(An unordered list: Aarav - 10th, Diya - 9th, Vikram - 11th, Meera - 10th)
Use for...of to loop through the array. Create DOM elements.
const students = [
  { name: "Aarav", grade: "10th" },
  { name: "Diya", grade: "9th" },
  { name: "Vikram", grade: "11th" },
  { name: "Meera", grade: "10th" }
];

const ul = document.createElement("ul");
for (const student of students) {
  const li = document.createElement("li");
  li.textContent = student.name + " - " + student.grade;
  ul.appendChild(li);
}
document.body.appendChild(ul);

Challenge 8: Diamond Pattern

Hard
Write a program using nested loops to print a diamond pattern with 5 rows in the top half and 4 in the bottom half (total 9 rows).
Sample Input
(No input required)
Sample Output
* *** ***** ******* ********* ******* ***** *** *
Use nested for loops. Build the pattern as a string.
let pattern = "";
const n = 5;
// Top half
for (let i = 1; i <= n; i++) {
  pattern += " ".repeat(n - i);
  pattern += "*".repeat(2 * i - 1);
  pattern += "\n";
}
// Bottom half
for (let i = n - 1; i >= 1; i--) {
  pattern += " ".repeat(n - i);
  pattern += "*".repeat(2 * i - 1);
  pattern += "\n";
}
console.log(pattern);

Challenge 9: Prime Numbers in a Range

Hard
Arjun wants to find all prime numbers between 2 and 50. Write a program using nested loops. For each number, check if it is divisible by any number from 2 to its square root.
Sample Input
(No input required)
Sample Output
Primes: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
Use nested loops. Use break when a divisor is found.
let primes = "Primes:";
for (let num = 2; num <= 50; num++) {
  let isPrime = true;
  for (let i = 2; i <= Math.sqrt(num); i++) {
    if (num % i === 0) {
      isPrime = false;
      break;
    }
  }
  if (isPrime) {
    primes += " " + num;
  }
}
console.log(primes);

Challenge 10: Build a Color Grid on a Webpage

Hard
Write a program using nested loops to create a 5x5 grid of div elements on a webpage. Each div should be 60px by 60px. Use a different shade of blue for each cell, calculated as: rgb(0, 0, (row * 5 + col) * 10 + 50).
Sample Input
(No input required)
Sample Output
(A 5x5 grid of divs with increasingly darker shades of blue)
Use nested for loops. Create div elements and style them dynamically.
const container = document.createElement("div");
container.style.display = "grid";
container.style.gridTemplateColumns = "repeat(5, 60px)";
container.style.gap = "4px";

for (let row = 0; row < 5; row++) {
  for (let col = 0; col < 5; col++) {
    const div = document.createElement("div");
    const blue = (row * 5 + col) * 10 + 50;
    div.style.width = "60px";
    div.style.height = "60px";
    div.style.backgroundColor = `rgb(0, 0, ${blue})`;
    div.style.borderRadius = "4px";
    container.appendChild(div);
  }
}

document.body.appendChild(container);

Need to Review the Concepts?

Go back to the detailed notes for this chapter.

Read Chapter Notes

Want to learn web development with a live mentor?

Explore our Frontend Masterclass