1

It checks if the number is bigger or smaller or not and also if the user has quit by entering "q". But it doesn't catch invalid input like "&, *, (, p, ]" with "while(!guess)".

let guess = window.prompt('guess the number!');
const rand = Math.floor(Math.random() * 10) + 1;
let tries = 0;
while (!guess) {
  let guess = parseInt(prompt('enter a valid number'));
}

while (parseInt(guess) !== rand) {
  tries += 1;
  if (guess === 'q') {
    console.log('you have exited');
    break;
  }
  if (guess < rand) guess = prompt('enter higher!');
  else guess > rand;
  guess = prompt('enter lower!');
}

console.log(`correct number is : ${rand} and it took you ${tries} tries`);
1
  • Probably because you're not converting the initial guess to an integer. A value of "&" is a non-empty string and is therefore truthy, which means the first while loop would be skipped. Commented Apr 14, 2021 at 2:51

2 Answers 2

0

You can use else if between each conditional. Your final else would be something like, 'Invalid key pressed. Try again.'

if (guess === 'q') {...} else
if (parseInt(guess) < rand) {...} else
if (parseInt(guess) > rand {...}
else guess = prompt('Invalid key entered. Please try again.');
Sign up to request clarification or add additional context in comments.

Comments

0

You can compare the value of guess to see if it matches any of the special characters using Regex with String.test.

while (!guess || /[&*()\[\]p]/g.test(guess)) {
  let guess = prompt('enter a valid number');
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.