Examine the following code:
for (let a = 5; a > 1; a--) { console.log(a); } ;
Which statement can replace the for from the example above?
-
let a = 1; while (a < 5) console.log(a++);
-
let a = 5; while (a > 1) console.log(a++);
-
let a = 6; while (a >= 1) console.log(a--);
-
let a = 5; while (a > 1) console.log(a--);
Explanation & Hint:
A while loop is used to achieve the same iteration logic as the for loop. The while loop has the condition a > 1, which is the same as the for loop’s condition. The loop will continue executing as long as a is greater than 1. Inside the loop, console.log(a–) is used to display the value of a and then decrement it by 1. This is equivalent to the iteration statement in the for loop, which is a–. |