Analyze the following code:
for (let x = 10; x > 1; x -= 2) console.log("hello");
How many times will "hello"
be displayed in the console as a result of its execution?
- 5
- 9
- 10
- 4
Explanation & Hint:
The for loop is initialized with x set to 10. The loop condition is x > 1, and the loop’s iteration statement is x -= 2, which subtracts 2 from x in each iteration. The loop will continue executing as long as x is greater than 1. In each iteration, the code console.log(“hello”) is executed, which displays “hello” in the console. The loop starts with x = 10, and it will execute when x is greater than 1, subtracting 2 from x in each iteration. After the 5th iteration, x becomes 2, and the loop condition x > 1 evaluates to false, causing the loop to terminate. |