#13 For loop Conclusion; user prompt doesn't trigger if statement response


#1

Can someone tell me why the variable userChoice doesn't fulfill the if statement conditionals?
Everything gets printed out to the screen except for the if statement conditionals with one exception. The last 'else' always gets printed out to the screen and ignores the rest of the possible values of userChoice.


var states = ["Idaho", "New York", "Maryland", "Louisiana", "Kentucky"];
console.log("Listed states:");
for (i = 0; i < states.length; i++){
console.log(states[i]);
}
var userChoice = prompt("Choose a listed state by their corresponding number.");
console.log(userChoice);
if (userChoice === 1){
console.log("You decided to go with " + states[0] + ".");
}
else if (userChoice === 2){
console.log("You decided to go with " + states[1] + ".");
}
else if (userChoice === 3){
console.log("You decided to go with " + states[2] + ".");
}
else if (userChoice === 4){
console.log("You decided to go with " + states[3] + ".");
}
else if (userChoice === 5){
console.log("You decided to go with " + states[4] + ".");
}
else{
console.log("Not a valid State, retry.");
}


#2

Try == instead of ===?


#3

Well that certainly worked!
I thought that in javascript you must use 3 '=' signs to compare, after all the tutorials leading up to this lesson have always done comparison operators as

if (myChoice === 5){
//code goes here
};

thank you @jibblyj


#4

= is the assignment operator,
== is comparison of value,
=== is comparison of type and value:

var number;
number = 1; //Sets 'number' to 1.
number == 1; //Checks if number is equal to the value 1 or "1".
number === 1; //Checks if 'number' is of equal type and value as 1 - In this case it checks that 'number' is an integer (whole number) AND has the value 1.

above, the first example sets the variable number, the second checks if it's equal to 1 or "1" (integer or string), the last checks if it's an integer AND has the value of 1.