Home > Back-end >  How to compare a number in if condition?
How to compare a number in if condition?

Time:09-19

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;
    }
}

CodePudding user response:

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;
  }
}

CodePudding user response:

With number, input 0704 / 000704 has same value. It must be a "String".

  • Related