ARTICLE AD BOX
The loop is infinite by definition, since the test is always true.
It is the break statement that exits the loop. If req isn't set to "quit", then that break isn't reached.
1,7843 gold badges15 silver badges26 bronze badges
while (true) runs forever unless you stop it.
Since req is never updated, its value stays "list", so the same if condition is true every time and the loop repeats endlessly.
When you reassign req inside the loop, the value can change (like to "quit"), which lets the loop behave differently or stop.
New contributor
Ajithesh is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
your "req" variable in not updated.It should be inside the while loop.
let todo = []; while (true) { let req = prompt("Enter your request"); if (req === "quit") { console.log("You have exited from todo."); break; } if (req === "list") { console.log("Here is your todo list."); for (let i = 0; i < todo.length; i++) { console.log(i, todo[i]); } } }Your code can be formalised in following manner
while(<condition 1>){ if(<condition 2>){ break; } if(<condition 3>){ // Do something } }Now a while loop can be stopped two ways, either condition 1 becomes false or their is a break statement inside the loop which gets executed ( in your case the break statement is itself in a if block and will only get executed if condition 2 becomes true).
Since condition 1 is always true in your case, it cannot be used to stop the loop. Coming to condition 2 (evaluation of req), whenever this evaluates to true the break statement will be executed and the loop will end, but the value of req is being never updated and hence this condition always evaluates to false and the break statement is not being executed, so the result is infinite loop.
If you reassign req inside the loop to quit, when condition 2 gets evaluated next time it will evaluate to true and the break statement will get executed and the loop will terminate.
The correct way would to get input for req on every iteration and then evaluate it to whatever you want to.
New contributor
aman tripathi is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
Explore related questions
See similar questions with these tags.
