Newbie question about capitalized strings in condition statements

Hi all,
I’ve been studying javascript for about a week and wrote the following code just to test my knowledge…but I have a question: Why when the user types in “Bananas” in the prompt box with a capital B instead of “bananas” does it run the last condition instead of the first condition?


var $fruit = prompt('What fruit do monkeys like the most?', '');

if ($fruit == 'bananas') {
   document.write('That\\'s right!');
}
 else if ($fruit == 'meat') {
  document.write('They are not carnivores, idiot!');
}
  else ($fruit != 'meat' && $fruit != 'bananas') {
   document.write('Your answer sucks!');
}


Of course, I could do it the lazy way and use the logical AND operator (&&) as:

if ($fruit == 'bananas' && $fruit == 'Bananas' )

but, is there a better way?

Thanks!

Hi skunker,

Short answer: because string comparison is case sensitive.
“Bananas” is not the same as “bananas”

You need the || operator, not the && operator
You want to check if the answer is “bananas” OR “Bananas”

if ($fruit == 'bananas' || $fruit == 'Bananas') {

Not really.
You could write:

if ($fruit.toUpperCase() == 'BANANAS') {

but to my mind that is less readable.

On a side note, in JavaScript you don’t need to prefix your variables with a dollar sign like you do in PHP