SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Evangelist
    Join Date
    Oct 2004
    Location
    Texas
    Posts
    429
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    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?

    Code:
    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:
    Code:
    if ($fruit == 'bananas' && $fruit == 'Bananas' )
    but, is there a better way?

    Thanks!

  2. #2
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,313
    Mentioned
    178 Post(s)
    Tagged
    9 Thread(s)
    Hi skunker,

    Quote Originally Posted by skunker View Post
    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?
    Short answer: because string comparison is case sensitive.
    "Bananas" is not the same as "bananas"

    Quote Originally Posted by skunker View Post
    Of course, I could do it the lazy way and use the logical AND operator (&&) as:
    Code:
    if ($fruit == 'bananas' && $fruit == 'Bananas' )
    You need the || operator, not the && operator
    You want to check if the answer is "bananas" OR "Bananas"

    Code JavaScript:
    if ($fruit == 'bananas' || $fruit == 'Bananas') {

    Quote Originally Posted by skunker View Post
    but, is there a better way?
    Not really.
    You could write:

    Code JavaScript:
    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


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •