How many times will the code below output the string in the loop?
let x = 0
while (x < 5) {
console.log("in the loop");
}
I replied 5 times and my answer got marked as wrong to which I don’t understand why as the string should be printed 5 times, once for all the values of x = 0; x=1; x=2; x=3 and x=4.
Hey there,
The loop right now runs infinite number of times. Here’s why:
In the while loop you have a condition saying as long is x is less than 5, run a specific code. Now your x is equal to 0, and there is no change in the value of x. So it’s gonna keep running because it’s always 0. To make the loop work, you have to make the value of x change. For example you can add x++ which means increase the value of x by 1, after your console.log(). This way, when x is 0, the code will run and x will be equal to 1, then the loop will go on until x is equal to 5. And since 5 is not less than 5, it will stop. That way the loop will run only 5 times.
The issue is that x is never incremented inside the loop, so the condition x < 5 always stays true, causing an infinite loop. You’d need to add x++ inside the loop for it to run exactly 5 times.