Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to compare a number in if condition?

I wrote this code for the user to guess a password exactly 4 times but I am not able to compare the input with the pin, is the way I have compared here wrong? can I not compare the number directly? like

if (input !== 0704)

is it wrong if I’m writing the number directly like this? it works fine if I replace the number with a string.

let pin = 0704;
let count = 0;
for (i=1; i<=4; i++) {
    let input = prompt('please make a guess');
    if (input !== 0704 ) {
        console.log('Sorry that was wrong');
        count++;
    }
    else {
        console.log('That was correct!')
        break;
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

if by input you are meaning html input then you need to compare the value with a string since output of html input is in string format. Also note the preceding 0 in 0704 will be ignored. So in this case you can use 0704 as string and perform comparison

let pin = '0704';
let count = 0;
for (i = 1; i <= 4; i++) {
  let input = prompt('please make a guess');
  if (input !== pin) {
    console.log('Sorry that was wrong');
    count++;
  } else {
    console.log('That was correct!')
    break;
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading