This code keeps looping and looping. I'm using a do..while loop create a simple password checker however.. It keeps looping and looping any help will be greatly appreciated. Thanks
{
let password;
do {
password = prompt("Enter the code");
} while (password.toLowerCase() !== "jude" || "joel");
}
CodePudding user response:
This:
password.toLowerCase() !== "jude" || "joel"
is not actually what you think it does. It will always evaluate to true
, since "joel"
, when coerced to a boolean, is true
(See Truthy and Falsy values).
Demonstration:
You have to do the comparison again:
let password;
do {
password = prompt("Enter the code");
} while (password.toLowerCase() !== "jude" || password.toLowerCase() !== "joel");
Since you're only checking whether the password in lower case is equal or not (pointed out by MikeM), you can also just assign the result of the prompt after being converted to lower case to password
. This means we will only need to convert to lowercase once:
let password;
do {
password = prompt("Enter the code").toLowerCase();
} while (password !== "jude" || password !== "joel");
Or even better, store the valid passwords in an array and check whether it includes the password:
let password;
do {
password = prompt("Enter the code");
} while (!["jude", "joel"].includes(password.toLowerCase()));
CodePudding user response:
Another way that avoids the do while is to use a while with a break;
inside.
let password;
while (true) {
password = prompt("Enter the code");
if (["jude", "joel"].includes(password.toLowerCase())) {
break;
}
}