Discover for
, while
, and do-while
loops for repeating code execution in JavaScript.
for
, while
, and do-while
, each with their own specific use-cases.
This example demonstrates the use of different loop types in JavaScript:
// For loop
for (let i = 1; i <= 5; i++) {
console.log("For loop count:", i);
}
// While loop
let j = 1;
while (j <= 5) {
console.log("While loop count:", j);
j++;
}
// Do-while loop
let k = 1;
do {
console.log("Do-while loop count:", k);
k++;
} while (k <= 5);
This code demonstrates:
for
loop for a known number of iterations.while
loop for condition-based repetition.do-while
loop to ensure the block executes at least once.for (init; condition; increment)
.Q1: What is the minimum number of times a do-while
loop will execute?
Answer: B. 1
Q2: Which loop is ideal when the number of iterations is known beforehand?
Answer: C. for
Q3: What happens if the loop condition never becomes false in a while
loop?
Answer: B. It results in an infinite loop
Q4: Where is the loop condition evaluated in a do-while
loop?
Answer: B. After the loop body