Input validation not working?


#1
var characterStats = []; //ATTK,SPD,DEF
var characterHitPoints = 100;
var characterChoice = 0;
var loopy = true;

//Character Selection
do {
characterChoice = prompt("Choose your character type: (1/2/3)\n\n(1)Archer: A ranged combatant with a fast attack     speed. Archers can only be hit by ranged attacks.\n\n(2)Warrior: The warriors damage, speed and defense can very     greatly depending on the selection of short sword/shield combination or having just a long sword.\n\n(3)Barbarian: The barbarian is generally slow but extremely strong and has impressive defense.");

//input validation for character selection
if (characterChoice === 1){
    loopy = false;
} else if (characterChoice === 2) {
    loopy = false;
} else if (characterChoice === 3) {
    loopy = false;
} else { 
    loopy = true;
    alert("Please enter a valid character selection.");}
} while (loopy);

This seems to create an infinite loop or just doesn't work at all, anyone know why?


#2

That's because prompt function returns a string.

And, as you probably know "2" === 2 is false.

You can use "1", "2" and "3" instead of 1, 2 and 3. Or you can use == operator instead of ===.

Difference between == and === is quite simple, the first one tries to cast values of both operands to the same type before checking their equality. Example:

"2" === 2   // false
"2" == 2    // true

#3

So in this case the below would work as well?

2 == 2


#4

Yes, 2 == 2 will return true, but both operands are of the same type so you can use here === also.


#5

I understand now, thank you!


#6

You're very welcome :panda_face: